{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Title: #Sum Of Special Evenly-Spaced Elements In Array"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Difficulty: #Hard"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Category Title: #Algorithms"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Tag Slug: #array #dynamic-programming"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Name Translated: #数组 #动态规划"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Solution Name: solve"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translated Title: #数组中特殊等间距元素的和"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translated Content:\n",
    "<p>给定一个<strong>索引从 0 开始</strong>的整数类型数组 <code>nums</code> ，包含 <code>n</code> 个非负整数。</p>\n",
    "\n",
    "<p>另外给定一个（包含查询指令的）数组 <code>queries</code> ，其中 <code>queries[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>。 第 <code>i</code> 个查询指令的答案是 <code>nums[j]</code> 中满足该条件的所有元素的和： <code>x<sub>i</sub> &lt;= j &lt; n</code> 且 <code>(j - x<sub>i</sub>)</code> 能被 <code>y<sub>i</sub></code> 整除。</p>\n",
    "\n",
    "<p>返回一个数组<em> </em><code>answer</code>，其中<em>  </em><code>answer.length == queries.length</code> 且 <code>answer[i]</code> 是第 <code>i</code> 个查询指令的答案对 <code>10<sup>9 </sup>+ 7</code> 取模。</p>\n",
    "\n",
    "<p> </p>\n",
    "\n",
    "<p><strong>示例 1:</strong></p>\n",
    "\n",
    "<pre><strong>输入:</strong> nums = [0,1,2,3,4,5,6,7], queries = [[0,3],[5,1],[4,2]]\n",
    "<strong>输出:</strong> [9,18,10]\n",
    "<strong>解释:</strong> 每次查询的答案如下：\n",
    "1) 符合查询条件的索引 j 有 0、 3 和 6。 nums[0] + nums[3] + nums[6] = 9\n",
    "2) 符合查询条件的索引 j 有 5、 6 和 7。 nums[5] + nums[6] + nums[7] = 18\n",
    "3) 符合查询条件的索引 j 有 4 和 6。 nums[4] + nums[6] = 10\n",
    "</pre>\n",
    "\n",
    "<p><strong>示例 2:</strong></p>\n",
    "\n",
    "<pre><strong>输入:</strong> nums = [100,200,101,201,102,202,103,203], queries = [[0,7]]\n",
    "<strong>输出:</strong> [303]\n",
    "</pre>\n",
    "\n",
    "<p> </p>\n",
    "\n",
    "<p><b>提示：</b></p>\n",
    "\n",
    "<ul>\n",
    "\t<li><code>n == nums.length</code></li>\n",
    "\t<li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li>\n",
    "\t<li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n",
    "\t<li><code>1 &lt;= queries.length &lt;= 1.5 * 10<sup>5</sup></code></li>\n",
    "\t<li><code>0 &lt;= x<sub>i</sub> &lt; n</code></li>\n",
    "\t<li><code>1 &lt;= y<sub>i</sub> &lt;= 5 * 10<sup>4</sup></code></li>\n",
    "</ul>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Description: [sum-of-special-evenly-spaced-elements-in-array](https://leetcode.cn/problems/sum-of-special-evenly-spaced-elements-in-array/description/)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Solutions: [sum-of-special-evenly-spaced-elements-in-array](https://leetcode.cn/problems/sum-of-special-evenly-spaced-elements-in-array/solutions/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_cases = ['[0,1,2,3,4,5,6,7]\\n[[0,3],[5,1],[4,2]]', '[100,200,101,201,102,202,103,203]\\n[[0,7]]']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def find_list(self, g, x, solved):\n",
    "        res = 0\n",
    "        for u in g[x]:\n",
    "            if u not in solved:\n",
    "                solved.add(u)\n",
    "                res = max(res, self.find_list(g, u, solved) + 1)\n",
    "        return res\n",
    "\n",
    "    def maximumInvitations(self, favorite: List[int]) -> int:\n",
    "        # u->v for u like v\n",
    "        # x1->x2, x2->x1, x3->x1, x4->x1, then result is 3, if x6->x5->x2, then result is 5, \n",
    "        # if x9->x8->x7->x2, then result is 6, ...\n",
    "        # x1->x2, x2->x3, x3->x1, then result is 3, if x4->x1, then result is still 3\n",
    "        n = len(favorite)\n",
    "        solved = set()\n",
    "        res = 0  # 所有x1->x2->x3->x1都不能组合和扩展，答案是3\n",
    "        res2 = 0 # 所有x1->x2->x1及其扩展xi->...->x1,xj->...->x2都可以组合\n",
    "        # 如x1->x2->x1,x3->x4->x3，则答案是4\n",
    "\n",
    "        g = [[] for i in range(n)]\n",
    "        for i in range(n):\n",
    "            u = favorite[i]\n",
    "            g[u].append(i)\n",
    "\n",
    "        for i in range(n):\n",
    "            u = favorite[i]\n",
    "            if favorite[u] == i and i not in solved:\n",
    "                solved.add(u)\n",
    "                solved.add(i)\n",
    "                res2 += 2 + self.find_list(g, u, solved) + self.find_list(g, i, solved)\n",
    "        \n",
    "        # print(solved, res2)\n",
    "        for i in range(n):\n",
    "            if i not in solved:\n",
    "                u = favorite[i]\n",
    "                cnt = 0\n",
    "                tmp = {i: cnt}\n",
    "                while u not in solved:\n",
    "                    cnt += 1\n",
    "                    tmp[u] = cnt \n",
    "                    solved.add(u)\n",
    "                    u = favorite[u]\n",
    "                # print(\"tmp=\",tmp, \"u=\", u)\n",
    "                if u in tmp:\n",
    "                    res = max(res, cnt + 1 - tmp[u])\n",
    "        \n",
    "        return max(res, res2)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# -*- coding: utf-8 -*-\n",
    "from typing import List, Tuple, Optional\n",
    "from collections import deque, Counter\n",
    "from queue import PriorityQueue\n",
    "import math\n",
    "from functools import lru_cache\n",
    "from sortedcontainers import SortedDict, SortedSet\n",
    "import random\n",
    "import copy\n",
    "\n",
    "import sys\n",
    "sys.setrecursionlimit(9999999)\n",
    "\n",
    "MOD = 10**9 + 7\n",
    "\n",
    "from typing import List\n",
    "\n",
    "'''  \n",
    "题目名 5816. 查询最大基因差  \n",
    "思路 离线计算，对于询问，按照节点进行分桶，DFS遍历整个树，每到一个节点将节点上的数加入到Trie, 回溯时候将数值删掉，检查到当前前是询问中包含  \n",
    "的点，就计算该点的所有询问，计算询问的方式就是简单的前缀树求最大异或和问题  \n",
    "'''\n",
    "\n",
    "from typing import List\n",
    "import sys\n",
    "\n",
    "sys.setrecursionlimit(999999)\n",
    "\n",
    "\n",
    "class TrieNode:\n",
    "    def __init__(self):\n",
    "        self.next = [None, None]\n",
    "        self.cnt = 0\n",
    "\n",
    "\n",
    "class Trie:\n",
    "    def __init__(self):\n",
    "        self.root = TrieNode()\n",
    "\n",
    "    def add_val(self, val):\n",
    "        cur = self.root\n",
    "        for i in range(17, -1, -1):\n",
    "            ch = 0 if val & (1 << i) == 0 else 1\n",
    "            if cur.next[ch] is None:\n",
    "                new_node = TrieNode()\n",
    "                cur.next[ch] = new_node\n",
    "            cur = cur.next[ch]\n",
    "            cur.cnt += 1\n",
    "\n",
    "    def del_val(self, val):\n",
    "        cur = self.root\n",
    "        for i in range(17, -1, -1):\n",
    "            ch = 0 if val & (1 << i) == 0 else 1\n",
    "\n",
    "            cur.next[ch].cnt -= 1\n",
    "            if cur.next[ch].cnt != 0:\n",
    "                cur = cur.next[ch]\n",
    "            else:\n",
    "                cur.next[ch] = None\n",
    "                break\n",
    "\n",
    "    def getRoot(self) -> TrieNode:\n",
    "        return self.root\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def maxGeneticDifference(self, parents: List[int], queries: List[List[int]]) -> List[int]:\n",
    "        qq = {}\n",
    "        link = {i: [] for i in range(len(parents))}\n",
    "\n",
    "        for idx, (node, val) in enumerate(queries):\n",
    "            if node not in qq:\n",
    "                qq[node] = []\n",
    "            qq[node].append((val, idx))\n",
    "\n",
    "        root = None\n",
    "        for node, p in enumerate(parents):\n",
    "            if p == -1:\n",
    "                root = node\n",
    "            else:\n",
    "                link[p].append(node)\n",
    "\n",
    "        valid = [False] * len(parents)\n",
    "\n",
    "        def dfs(node):\n",
    "            flag = False\n",
    "            if node in qq.keys():\n",
    "                flag = True\n",
    "\n",
    "            cnt = 0\n",
    "            for ne in link[node]:\n",
    "                if dfs(ne):\n",
    "                    cnt += 1\n",
    "\n",
    "            if flag or cnt > 0:\n",
    "                valid[node] = True\n",
    "\n",
    "            return valid[node]\n",
    "\n",
    "        dfs(root)\n",
    "\n",
    "        trie = Trie()\n",
    "        ret = [0] * len(queries)\n",
    "\n",
    "        def solve(node):\n",
    "            if valid[node] == False:\n",
    "                return\n",
    "\n",
    "            trie.add_val(node)\n",
    "            if node in qq.keys():\n",
    "                for val, idx in qq[node]:\n",
    "                    cur = trie.getRoot()\n",
    "                    ans = 0\n",
    "                    for i in range(18):\n",
    "                        if val & (1 << (17 - i)) == 0:\n",
    "                            if cur.next[1] is not None:\n",
    "                                cur = cur.next[1]\n",
    "                                ans |= (1 << (17 - i))\n",
    "                            else:\n",
    "                                cur = cur.next[0]\n",
    "                        else:\n",
    "                            if cur.next[0] is not None:\n",
    "                                cur = cur.next[0]\n",
    "                                ans |= (1 << (17 - i))\n",
    "                            else:\n",
    "                                cur = cur.next[1]\n",
    "\n",
    "                    ret[idx] = max(ret[idx], ans)\n",
    "\n",
    "            for ne in link[node]:\n",
    "                solve(ne)\n",
    "\n",
    "            trie.del_val(node)\n",
    "\n",
    "        solve(root)\n",
    "        return ret"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def maxLength(self, arr: List[str]) -> int:\n",
    "        # Draw a tree, solve get ans, get all possible concatenated strings\n",
    "        res = []\n",
    "        path = []\n",
    "        \n",
    "        def dfs(arr, path, res):\n",
    "            if not arr: # arr is empty\n",
    "                res.append(path)\n",
    "                return\n",
    "\n",
    "            # trim, if we can add arr[0] to current path?\n",
    "            new_path = ''.join(path + [arr[0]])\n",
    "            if len(set(list(new_path))) == len(new_path):\n",
    "                dfs(arr[1:], path+[arr[0]], res)\n",
    "            dfs(arr[1:], path, res)\n",
    "\n",
    "        dfs(arr, path, res)\n",
    "        ans = [len(''.join(item)) for item in res]\n",
    "        #print(ans)\n",
    "        return max(ans)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def getMaxLen(self, nums: List[int]) -> int:\n",
    "        def solve(nums):\n",
    "            if not nums:\n",
    "                return 0\n",
    "            dp = [[0 for i in range(len(nums))] for j in range(2)]\n",
    "            for i in range(len(nums)):\n",
    "                if nums[i]>0:\n",
    "                    dp[0][i] = 1\n",
    "                else:\n",
    "                    dp[1][i] = 1\n",
    "            max_length = dp[0][0]\n",
    "            for i in range(1,len(nums)):\n",
    "                if nums[i] >0:\n",
    "                    if dp[0][i-1]>0:\n",
    "                        dp[0][i] = max(dp[0][i],dp[0][i-1]+1)\n",
    "                    if dp[1][i-1] > 0 :\n",
    "                        dp[1][i] = max(dp[1][i],dp[1][i-1]+1)\n",
    "\n",
    "                elif nums[i] <0:\n",
    "                    if dp[1][i-1] > 0 :\n",
    "                        dp[0][i] = max(dp[0][i],dp[1][i-1]+1)\n",
    "                    if dp[0][i-1] > 0 :\n",
    "                        dp[1][i] = max(dp[1][i],dp[0][i-1]+1)\n",
    "\n",
    "                max_length = max(max_length,dp[0][i])\n",
    "            print(dp)\n",
    "            return max_length\n",
    "        \n",
    "        \n",
    "        nums = [0] + nums + [0]\n",
    "        start = 0\n",
    "        ans = 0\n",
    "        for i,num in enumerate(nums):\n",
    "            if i == 0:\n",
    "                continue\n",
    "            elif nums[i] == 0:\n",
    "                ans = max(ans,solve(nums[start+1:i]))\n",
    "                start = i\n",
    "                \n",
    "        return ans\n",
    "                \n",
    "        \n",
    "        \n",
    "                    \n",
    "                \n",
    "                \n",
    "            \n",
    "                \n",
    "            \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subarrayLCM(self, nums: List[int], k: int) -> int:\n",
    "        nums.append(k + 1)\n",
    "        res, N = 0, len(nums)\n",
    "        l = 0\n",
    "\n",
    "        #print(nums)\n",
    "        #print('================')\n",
    "\n",
    "        def lcm(a, b):\n",
    "            return a * b // math.gcd(a, b)\n",
    "\n",
    "\n",
    "        def resolve(l, r):\n",
    "            if r < l: return 0\n",
    "\n",
    "            res = 0\n",
    "\n",
    "            #print(l, r, '----------------')\n",
    "            for i in range(l, r + 1):\n",
    "                #print(i,'----------------')\n",
    "                tmp = nums[i]\n",
    "                for j in range(i, l - 1, -1):\n",
    "                    tmp = lcm(tmp, nums[j])\n",
    "                    #print(':', j, i ,'     ', nums[j], nums[i])\n",
    "                    if tmp == k:\n",
    "                        #print('add ',j)\n",
    "                        res += 1\n",
    "                    elif tmp > k:\n",
    "                        break\n",
    "\n",
    "            #print('-> ',res)\n",
    "            return res\n",
    "\n",
    "        \n",
    "        for r in range(N):\n",
    "            if k % nums[r] == 0:\n",
    "                continue\n",
    "            else:\n",
    "                res += resolve(l, r - 1)\n",
    "                l = r + 1\n",
    "\n",
    "\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subarrayLCM(self, nums: List[int], k: int) -> int:\n",
    "        nums.append(k + 1)\n",
    "        res, l = 0, 0\n",
    "\n",
    "        def resolve(l, r):\n",
    "            if r < l: return 0\n",
    "            res = 0\n",
    "            for i in range(l, r + 1):\n",
    "                tmp = nums[i]\n",
    "                for j in range(i, l - 1, -1):\n",
    "                    tmp = tmp * nums[j] // math.gcd(tmp, nums[j])\n",
    "                    if tmp == k:\n",
    "                        res += 1\n",
    "                    elif tmp > k:\n",
    "                        break\n",
    "            return res\n",
    "\n",
    "        \n",
    "        for r in range(len(nums)):\n",
    "            if k % nums[r] != 0:\n",
    "                res += resolve(l, r - 1)\n",
    "                l = r + 1\n",
    "\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        def check(st):\n",
    "            a = b = i = 0\n",
    "            m = len(st)\n",
    "            while i<m:\n",
    "                cur = st[i]\n",
    "                while i+1 < m and st[i+1] not in \"+-\":\n",
    "                    cur += st[i+1]\n",
    "                    i+=1\n",
    "                if cur[-1] == \"x\":\n",
    "                    cur = cur[:-1]\n",
    "                    a += int(cur) if cur and cur not in \"+-\" else int(cur+\"1\")\n",
    "                else:\n",
    "                    b += int(cur)\n",
    "                i+=1\n",
    "            return [a,b]\n",
    "        lst = equation.split(\"=\")\n",
    "        a1, b1 = check(lst[0])\n",
    "        a2, b2 = check(lst[1])\n",
    "        if a1 == a2:\n",
    "            return \"Infinite solutions\" if b1==b2 else \"No solution\"\n",
    "        ans = (b2-b1) // (a1-a2)\n",
    "        return f\"x={ans}\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        left_num, right_num = 0, 0\n",
    "        left_x, right_x = 0, 0\n",
    "        sign = 1\n",
    "        temp_str = ''\n",
    "        equ_left = True\n",
    "        for i, ch in enumerate(equation):\n",
    "\n",
    "            if ch.isdigit():\n",
    "                temp_str += ch \n",
    "            elif ch == 'x':\n",
    "                if temp_str == '': temp_str = '1'\n",
    "\n",
    "                if equ_left:\n",
    "                    left_x = left_x + sign * int(temp_str)\n",
    "                else:\n",
    "                    right_x = right_x + sign * int(temp_str)\n",
    "\n",
    "                temp_str = ''\n",
    "                sign = 1\n",
    "            elif ch in ('+', '-', '='):\n",
    "                if temp_str != '': \n",
    "                    if equ_left:\n",
    "                        left_num = left_num + sign * int(temp_str)\n",
    "                    else:\n",
    "                        right_num = right_num + sign * int(temp_str)\n",
    "\n",
    "                temp_str = ''\n",
    "                if ch == '+': sign = 1\n",
    "                elif ch == '-': sign = -1\n",
    "\n",
    "            if (i == len(equation) - 1 or ch == '=') and temp_str != '':\n",
    "                if equ_left:\n",
    "                    left_num = left_num + sign * int(temp_str)\n",
    "                else:\n",
    "                    right_num = right_num + sign * int(temp_str)\n",
    "                temp_str = ''\n",
    "                sign = 1\n",
    "\n",
    "            if ch == '=':\n",
    "                equ_left = False\n",
    "                sign = 1\n",
    "\n",
    "            # print(ch, left_num, left_x, left_num, right_x,right_num)\n",
    "\n",
    "        if left_x == right_x and left_num == right_num: return \"Infinite solutions\"\n",
    "        if left_x == right_x and left_num != right_num: return \"No solution\"\n",
    "        # print(left_num, right_num, left_x, right_x)\n",
    "        ans = (right_num - left_num) // (left_x - right_x)\n",
    "        return 'x={}'.format(str(ans))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        left,right=equation.split(\"=\")\n",
    "        if left==right:\n",
    "            return  \"Infinite solutions\"\n",
    "        start=0\n",
    "        listx=[]\n",
    "        listn=[]\n",
    "        for i in range(len(left)):\n",
    "            if left[i]==\"x\":\n",
    "                start=i+1\n",
    "                end=i\n",
    "                if i == 0:\n",
    "                    listx.append(1)\n",
    "                elif left[i-1]==\"+\"or left[i-1]==\"-\":\n",
    "                    if left[i-1]==\"+\":\n",
    "                        listx.append(1)\n",
    "                    elif left[i-1]==\"-\":\n",
    "                        listx.append(-1)\n",
    "\n",
    "                else:\n",
    "                    while (left[end]!=\"-\" and left[end]!=\"+\") :\n",
    "                        end-=1\n",
    "                        if end<0:\n",
    "                            break\n",
    "\n",
    "                    end=end+1\n",
    "                    if end <=0:\n",
    "                        listx.append(int(left[0:i]))\n",
    "                    elif left[end-1]==\"-\":\n",
    "                        listx.append(-int(left[end:i]))\n",
    "                    elif left[end-1]==\"+\":\n",
    "                        listx.append(int(left[end:i]))\n",
    "\n",
    "\n",
    "            if left[i]==\"+\"or left[i]==\"-\":\n",
    "                if left[start:i]!=\"\":\n",
    "                    listn.append(-int(left[start:i]))\n",
    "                    start=i\n",
    "        if left[-1]!=\"x\":\n",
    "            listn.append(-int(left[start:]))\n",
    "\n",
    "        start=0\n",
    "        for i in range(len(right)):\n",
    "            if right[i]==\"x\":\n",
    "                start=i+1\n",
    "                end=i\n",
    "                if i == 0:\n",
    "                    listx.append(-1)\n",
    "                elif right[i-1]==\"+\"or  right[i-1]==\"-\":\n",
    "                    if right[i-1]==\"+\":\n",
    "                        listx.append(-1)\n",
    "                    elif right[i-1]==\"-\":\n",
    "                        listx.append(1)\n",
    "                else:\n",
    "                    while (right[end]!=\"-\" and right[end]!=\"+\") :\n",
    "                        end-=1\n",
    "                        if end<0:\n",
    "                            break\n",
    "                    end=end+1\n",
    "                    if end <=0:\n",
    "                        listx.append(-int(right[0:i]))\n",
    "                    elif right[end-1]==\"-\":\n",
    "                        listx.append(int(right[end:i]))\n",
    "                    elif right[end-1]==\"+\":\n",
    "                        listx.append(-int(right[end:i]))\n",
    "\n",
    "            if right[i]==\"+\"or right[i]==\"-\":\n",
    "                if right[start:i]!=\"\":\n",
    "                    listn.append(int(right[start:i]))\n",
    "\n",
    "                    start=i\n",
    "        if right[-1]!=\"x\":\n",
    "            listn.append(int(right[start:]))\n",
    "\n",
    "        sumx=sum(listx)\n",
    "        sumn=sum(listn)\n",
    "        if sumx==0 and sumn!=0:\n",
    "            return \"No solution\"\n",
    "        elif sumx==0 and sumn==0:\n",
    "            return \"Infinite solutions\"\n",
    "        elif sumn==0:\n",
    "            return \"x=0\"\n",
    "        else:\n",
    "            k=sumn//sumx\n",
    "            return \"x=\"+str(k)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        n = len(equation)\n",
    "        i = 0\n",
    "        sign = 1\n",
    "        factor,val = 0,0\n",
    "        while i < n:\n",
    "            if equation[i] == \"=\":\n",
    "                sign = -1\n",
    "                i += 1\n",
    "                continue\n",
    "            s = sign\n",
    "            if equation[i] == \"+\":\n",
    "                i += 1\n",
    "            if equation[i] == \"-\":\n",
    "                s *= -1\n",
    "                i += 1\n",
    " \n",
    "\n",
    "            value = False\n",
    "            num = 0\n",
    "            while i < n and equation[i].isdigit():\n",
    "                value = True\n",
    "                num = num*10 + int(equation[i])\n",
    "                i += 1 \n",
    "\n",
    "            if i < n and equation[i] == \"x\":\n",
    "                factor += num*s if value else s \n",
    "                i += 1\n",
    "            else:\n",
    "                val += num*s \n",
    "        \n",
    "        if factor == 0 and val == 0:\n",
    "            return \"Infinite solutions\"\n",
    "        if factor == 0 and val != 0:\n",
    "            return \"No solution\"\n",
    "        print(factor)\n",
    "        print(val)\n",
    "        return f\"x={-val//factor}\" \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        def f(e):\n",
    "            e += '+'\n",
    "            sign = 1\n",
    "            c,x = 0,0\n",
    "            seg = ''\n",
    "            for ch in e:\n",
    "                if ch not in '+-':\n",
    "                    seg += ch\n",
    "                else:\n",
    "                    if 'x' in seg:\n",
    "                        if len(seg) == 1:\n",
    "                            x += sign\n",
    "                        else:\n",
    "                            x += sign * int(seg[:-1])\n",
    "                    elif len(seg) > 0:\n",
    "                        c += sign * int(seg)\n",
    "\n",
    "                    seg = ''\n",
    "                    sign = 1 if ch == '+' else -1\n",
    "\n",
    "            return c,x\n",
    "\n",
    "        left, right = equation.split('=')\n",
    "        c1,x1 = f(left)\n",
    "        c2,x2 = f(right)\n",
    "\n",
    "        if c1 == c2 and x1 == x2:\n",
    "            return \"Infinite solutions\"\n",
    "        elif x1 == x2 or (c2-c1)%(x1-x2) != 0:\n",
    "            return \"No solution\"\n",
    "        else:\n",
    "            return 'x=' + str((c2-c1)//(x1-x2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        left, right = '', ''\n",
    "        i = 0\n",
    "        while equation[i] != '=':\n",
    "            left += equation[i]\n",
    "            i += 1\n",
    "        right = equation[i + 1:]\n",
    "    \n",
    "        left_total, left_var = self.calculate(left)\n",
    "        right_total, right_var = self.calculate(right)\n",
    "        if left_var == right_var:\n",
    "            if left_total == right_total:\n",
    "                return \"Infinite solutions\"\n",
    "            else:\n",
    "                return \"No solution\"\n",
    "        diff_var = left_var - right_var\n",
    "        diff_total = right_total - left_total\n",
    "        if diff_total % diff_var == 0:\n",
    "            return \"x={}\".format(diff_total // diff_var)\n",
    "        return \"No solution\"\n",
    "\n",
    "    def calculate(self, string):\n",
    "        total, num_signs = 0, 0\n",
    "        i = 0\n",
    "        while i < len(string):\n",
    "            sign, tmp = '', ''\n",
    "            if string[i] in ['+', '-']:\n",
    "                sign = string[i]\n",
    "                i += 1\n",
    "            while i < len(string) and '0' <= string[i] <= '9':\n",
    "                if not sign:\n",
    "                    sign = '+'\n",
    "                tmp += string[i] \n",
    "                i += 1\n",
    "            if i < len(string) and string[i] == 'x':\n",
    "                if not tmp:\n",
    "                    tmp = '1'\n",
    "                if not sign or sign == '+':\n",
    "                    num_signs += int(tmp)\n",
    "                else:\n",
    "                    num_signs -= int(tmp)\n",
    "                i += 1\n",
    "                continue\n",
    "            total += eval(sign + tmp)\n",
    "        return total, num_signs\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        numlst = []\n",
    "        xlst = []\n",
    "\n",
    "\n",
    "        left = equation.split('=')[0].replace('-','+-').split('+')\n",
    "        for i in left:\n",
    "            if i == '':\n",
    "                continue\n",
    "            elif i == '-x':\n",
    "                xlst.append(-1)\n",
    "                continue\n",
    "\n",
    "            if 'x' in i:\n",
    "                xlst.append( int(i.replace('x','')) if i.replace('x','') != '' else 1)\n",
    "            else:\n",
    "                numlst.append(int(i))\n",
    "\n",
    "\n",
    "        right = equation.split('=')[1].replace('-','+-').split('+')\n",
    "        for i in right:\n",
    "            if i == '':\n",
    "                continue\n",
    "            elif i == '-x':\n",
    "                xlst.append(1)\n",
    "                continue\n",
    "\n",
    "            if 'x' in i:\n",
    "                xlst.append(-1*int(i.replace('x','')) if i.replace('x','') != '' else -1)\n",
    "            else:\n",
    "                numlst.append(-1*int(i))\n",
    "        \n",
    "\n",
    "        if sum(numlst) == 0 and sum(xlst) == 0:\n",
    "            return \"Infinite solutions\"\n",
    "        \n",
    "        if sum(numlst) != 0 and sum(xlst) == 0:\n",
    "            return \"No solution\"\n",
    "        \n",
    "        xvalue = -1 * sum(numlst) // sum(xlst)\n",
    "        if xvalue != -1*sum(numlst)/sum(xlst):\n",
    "            return \"No solution\"\n",
    "        return f\"x={str(xvalue)}\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "      left, right = equation.split('=')\n",
    "\n",
    "      def cook(x):\n",
    "        x = x.replace('+', ' + ')\n",
    "        x = x.replace('-', ' - ')\n",
    "        x = x.split()\n",
    "        return x\n",
    "\n",
    "      left = cook(left)\n",
    "      right = cook(right)\n",
    "\n",
    "      def calc(x):\n",
    "        cnt = 0\n",
    "        val = 0\n",
    "\n",
    "        def add(y):\n",
    "          nonlocal cnt, val\n",
    "          if y == 'x':\n",
    "            cnt += 1\n",
    "            return\n",
    "          if y.endswith('x'):\n",
    "            cnt += int(y[:-1])\n",
    "            return\n",
    "          val += int(y)\n",
    "\n",
    "        def sub(y):\n",
    "          nonlocal cnt, val\n",
    "          if y == 'x':\n",
    "            cnt -= 1\n",
    "            return\n",
    "          if y.endswith('x'):\n",
    "            cnt -= int(y[:-1])\n",
    "            return\n",
    "          val -= int(y)\n",
    "\n",
    "        i = 0\n",
    "        while i < len(x):\n",
    "          if x[i] == '+':\n",
    "            add(x[i+1])\n",
    "            i += 2\n",
    "            continue\n",
    "          if x[i] == '-':\n",
    "            sub(x[i+1])\n",
    "            i += 2\n",
    "            continue\n",
    "          add(x[i])\n",
    "          i += 1\n",
    "      \n",
    "        return cnt, val\n",
    "      \n",
    "      cnt_left, val_left = calc(left)\n",
    "      cnt_right, val_right = calc(right)\n",
    "\n",
    "      cnt_left -= cnt_right\n",
    "      val_right -= val_left\n",
    "\n",
    "      if cnt_left == 0:\n",
    "        if val_right == 0:\n",
    "          return \"Infinite solutions\"\n",
    "        return \"No solution\"\n",
    "      return \"x=%d\" % (val_right // cnt_left)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        factor = 0\n",
    "        val = 0\n",
    "        i = 0\n",
    "        n = len(equation)\n",
    "        sign = 1\n",
    "        while i < n:\n",
    "            if equation[i] == '=':\n",
    "                 sign = -1\n",
    "                 i += 1\n",
    "                 continue\n",
    "            s = sign\n",
    "            if equation[i] == '+':\n",
    "                i += 1\n",
    "            elif equation[i] == '-':\n",
    "                s = -s\n",
    "                i += 1\n",
    "            num = 0\n",
    "            valid = False\n",
    "            while i < n and equation[i].isdigit():\n",
    "                valid = True\n",
    "                num = num * 10 + int(equation[i])\n",
    "                i += 1\n",
    "            if i < n and equation[i] == 'x':\n",
    "                factor += s * num if valid else s\n",
    "                i += 1\n",
    "            else:\n",
    "                val += s * num\n",
    "\n",
    "        if factor == 0:\n",
    "            return 'No solution' if val else 'Infinite solutions'\n",
    "        return f'x={-val // factor}'\n",
    "         \n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        a, b, sign = 0, 0, 1\n",
    "        length = len(equation)\n",
    "        index = 0\n",
    "\n",
    "        while index < length:\n",
    "\n",
    "            if equation[index] == \"=\":\n",
    "                sign = sign*(-1)\n",
    "                index += 1\n",
    "\n",
    "                continue\n",
    "\n",
    "            sign_tmp = sign\n",
    "\n",
    "            if equation[index] == \"+\":\n",
    "                index += 1\n",
    "            elif equation[index] == \"-\":\n",
    "                sign_tmp = sign_tmp*(-1)\n",
    "                index += 1\n",
    "            \n",
    "            digit_num, flag = 0, False\n",
    "            while index < length and (\"0\" <= equation[index] <= \"9\"):\n",
    "                digit_num = 10*digit_num + int(equation[index])\n",
    "                index += 1\n",
    "                flag = True\n",
    "\n",
    "            if index < length and equation[index] == \"x\":\n",
    "                if flag:\n",
    "                    a = a + sign_tmp*digit_num\n",
    "                else:\n",
    "                    a = a + sign_tmp\n",
    "                index += 1\n",
    "            else:\n",
    "                b = b + sign_tmp*digit_num\n",
    "\n",
    "        if a == 0:\n",
    "            return \"No solution\" if b else \"Infinite solutions\"\n",
    "\n",
    "        return f\"x={-b//a}\"\n",
    "\n",
    "            \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "       # part求解的部分， flag 为1 左边 -1 为右边\n",
    "        def get_part(ans, part, flag):\n",
    "            for part in part.split('+'):\n",
    "                if not part:\n",
    "                    continue\n",
    "                #当前为x项\n",
    "                if part[-1] == 'x':\n",
    "                    #判断当前系数是否1\n",
    "                    if len(part) == 1:\n",
    "                        ans[1] += flag\n",
    "                    elif len(part) == 2 and part[0] == '-':\n",
    "                        ans[1] += -flag \n",
    "                    else:\n",
    "                        ans[1] += int(part[:-1]) * flag\n",
    "                else:\n",
    "                    ans[0] += int(part) * flag\n",
    "        #将-替换为+-\n",
    "        equation = equation.replace(\"-\", \"+-\")\n",
    "        # 将等式分为两部分\n",
    "        left, right = equation.split('=')\n",
    "        # 定义ans ans[0] 为常数项 ans[1] 为1此项\n",
    "        ans = [0, 0]\n",
    "        get_part(ans, left, 1)\n",
    "        get_part(ans, right, -1)\n",
    "\n",
    "        #比较系数项\n",
    "        if ans[1] == 0:\n",
    "            if ans[0] == 0:\n",
    "                return \"Infinite solutions\"\n",
    "            return \"No solution\"      \n",
    "        return f'x={-1*ans[0] // ans[1]}'\n",
    "\n",
    "    \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        n = len(equation)\n",
    "        def getXa(s):\n",
    "            # 获取x系数\n",
    "            def help(curS):\n",
    "                if len(curS) == 1:\n",
    "                    return 1\n",
    "                else:\n",
    "                    return int(curS[:-1])\n",
    "            if len(s) == 1:\n",
    "                return help(s)\n",
    "            elif '+' in s:\n",
    "                return help(s[1:])\n",
    "            elif '-' in s:\n",
    "                return -help(s[1:])\n",
    "            else:\n",
    "                return help(s)\n",
    "        def getDigit(s):\n",
    "            a, b = 0, 0\n",
    "            tmpS = s\n",
    "            while tmpS:\n",
    "                plusIdx, minsIdx = float(\"-inf\"), float(\"-inf\")\n",
    "                if '+' in tmpS:\n",
    "                    plusIdx = tmpS.rindex('+')\n",
    "                if '-' in tmpS:\n",
    "                    minsIdx = tmpS.rindex('-')\n",
    "                if plusIdx == minsIdx == float(\"-inf\"):\n",
    "                    if 'x' in tmpS:\n",
    "                        a += getXa(tmpS)\n",
    "                    else:\n",
    "                        b += int(tmpS)\n",
    "                    tmpS = ''\n",
    "                else:\n",
    "                    splitIdx = max(plusIdx, minsIdx)\n",
    "                    curS = tmpS[splitIdx:]\n",
    "                    if 'x' in curS:\n",
    "                        a += getXa(curS)\n",
    "                    else:\n",
    "                        b += int(curS)\n",
    "                    tmpS = tmpS[:splitIdx]\n",
    "            return a, b\n",
    "        leftS, rightS = equation.split('=')\n",
    "        leftA, leftB = getDigit(leftS)\n",
    "        rightA, rightB = getDigit(rightS)\n",
    "\n",
    "        a = leftA - rightA\n",
    "        b = rightB - leftB\n",
    "        if a == 0 and b != 0:\n",
    "            return \"No solution\"\n",
    "        if a == 0 and b == 0:\n",
    "            return \"Infinite solutions\"\n",
    "        return f\"x={int(b // a)}\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        sign,cur,num,k,left,has = 1,0,0,0,True,False\n",
    "        for c in equation + \"=\":\n",
    "            if c in \"-+=x\":\n",
    "                if c == \"x\":\n",
    "                    if not has and not cur:\n",
    "                        cur = 1\n",
    "                    k += sign * cur if left else -sign * cur \n",
    "                else:\n",
    "                    num += sign * cur if not left else -sign * cur\n",
    "                cur,has = 0,False\n",
    "            match c:\n",
    "                case \"-\":\n",
    "                    sign = -1\n",
    "                case \"+\":\n",
    "                    sign = 1\n",
    "                case \"=\":\n",
    "                    sign,left = 1, False\n",
    "                case \"x\":\n",
    "                    pass\n",
    "                case _:\n",
    "                    cur, has = cur * 10 + int(c), True \n",
    "        if not k:\n",
    "            return \"No solution\" if num else \"Infinite solutions\"\n",
    "        return f\"x={num//k}\" if not (num % k) else \"No solution\"\n",
    "\n",
    "                \n",
    "                "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        factor = val = 0\n",
    "        i, n, sign = 0, len(equation), 1  # 等式左边默认系数为正\n",
    "        while i < n:\n",
    "            if equation[i] == '=':\n",
    "                sign = -1\n",
    "                i += 1\n",
    "                continue\n",
    "\n",
    "            s = sign\n",
    "            if equation[i] == '+':  # 去掉前面的符号\n",
    "                i += 1\n",
    "            elif equation[i] == '-':\n",
    "                s = -s\n",
    "                i += 1\n",
    "\n",
    "            num, valid = 0, False\n",
    "            while i < n and equation[i].isdigit():\n",
    "                valid = True\n",
    "                num = num * 10 + int(equation[i])\n",
    "                i += 1\n",
    "\n",
    "            if i < n and equation[i] == 'x':  # 变量\n",
    "                factor += s * num if valid else s\n",
    "                i += 1\n",
    "            else:  # 数值\n",
    "                val += s * num\n",
    "\n",
    "        if factor == 0:\n",
    "            return \"No solution\" if val else \"Infinite solutions\"\n",
    "        return f\"x={-val // factor}\"\n",
    " "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def ansys(self, equation):\n",
    "        factor, constant = 0, 0\n",
    "        i = 0\n",
    "        while(i<len(equation)):\n",
    "            if equation[i]=='+':\n",
    "                start = i+1\n",
    "                j = i+1\n",
    "                while(j<len(equation) and equation[j]!='x' and equation[j]!='-' and equation[j]!='+'):\n",
    "                    j+=1\n",
    "                if j<len(equation) and equation[j]=='x':\n",
    "                    if start==j:\n",
    "                        factor += 1\n",
    "                    else:\n",
    "                        factor += int(equation[start: j])\n",
    "                    i = j+1\n",
    "                else:\n",
    "                    constant += int(equation[start: j])\n",
    "                    i=j\n",
    "            else:\n",
    "                start = i+1\n",
    "                j = i+1\n",
    "                while(j<len(equation) and equation[j]!='x' and equation[j]!='-' and equation[j]!='+'):\n",
    "                    j+=1\n",
    "                if j<len(equation) and equation[j]=='x':\n",
    "                    if start==j:\n",
    "                        factor -= 1\n",
    "                    else:\n",
    "                        factor -= int(equation[start: j])\n",
    "                    i = j+1\n",
    "                else:\n",
    "                    constant -= int(equation[start: j])\n",
    "                    i = j\n",
    "        return factor, constant\n",
    "                \n",
    "\n",
    "\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        leftEquation, rightEquation = equation.split('=')[0], equation.split('=')[1]\n",
    "        factor, constant = 0, 0\n",
    "        if leftEquation[0]!='-':\n",
    "            leftEquation = '+'+leftEquation\n",
    "        if rightEquation[0]!='-':\n",
    "            rightEquation = '+'+rightEquation\n",
    "        factorLeft, constantLeft = self.ansys(leftEquation)\n",
    "        factorRight, constantRight = self.ansys(rightEquation)\n",
    "        factor = factorLeft-factorRight\n",
    "        constant = constantRight-constantLeft\n",
    "        if factor==0 and constant!=0: return \"No solution\"\n",
    "        elif factor==0 and constant==0: return \"Infinite solutions\" \n",
    "        else: return \"x=\"+str(int(constant/factor))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\r\n",
    "    def solveEquation(self, equation: str) -> str:\r\n",
    "        lis = [0, 0]\r\n",
    "        flag = False\r\n",
    "        i = 0\r\n",
    "        tmp = ''\r\n",
    "        while(i < len(equation)):\r\n",
    "            if i < len(equation):\r\n",
    "                if equation[i] in ('+', '-'):\r\n",
    "                    tmp = equation[i]\r\n",
    "                    i += 1\r\n",
    "                elif equation[i] == '=':\r\n",
    "                    flag = True\r\n",
    "                    tmp = ''\r\n",
    "                    i += 1\r\n",
    "                    continue\r\n",
    "\r\n",
    "            while(i < len(equation) and equation[i] not in ('+', '-', '=')):\r\n",
    "                tmp += equation[i]\r\n",
    "                i += 1\r\n",
    "            n = len(tmp)\r\n",
    "            ind = 1\r\n",
    "            if 'x' in tmp:\r\n",
    "                tmp = tmp[:n-1]\r\n",
    "                ind = 0\r\n",
    "            if not flag:\r\n",
    "                if tmp == '' or tmp == '+' or tmp == '-':\r\n",
    "                    tmp += '1'\r\n",
    "                lis[ind] += int(tmp)\r\n",
    "            else:\r\n",
    "                if tmp == '' or tmp == '+' or tmp == '-':\r\n",
    "                    tmp += '1'\r\n",
    "                lis[ind] -= int(tmp)\r\n",
    "\r\n",
    "        if lis[0] == 0:\r\n",
    "            if lis[1] == 0:\r\n",
    "                return('Infinite solutions')\r\n",
    "            else:\r\n",
    "                return('No solution')\r\n",
    "        val = -int(lis[1]) // lis[0]\r\n",
    "        return('x={0}'.format(val))\r\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        def lt640(s):\n",
    "            def parse(s):\n",
    "                stack=[]\n",
    "                coef,num=0,0\n",
    "                for ch in s:\n",
    "                    if ch not in ['+','-','x']:\n",
    "                        stack.append(ch)\n",
    "                    elif ch=='x':\n",
    "                        if stack:\n",
    "                            if stack==['+']:coef+=1\n",
    "                            elif stack==['-']:coef-=1\n",
    "                            else:coef+=int(''.join(stack))\n",
    "                            stack=[]\n",
    "                        else:coef+=1\n",
    "                    else:\n",
    "                        if stack:\n",
    "                            num+=int(''.join(stack))\n",
    "                        stack=[ch]\n",
    "                if stack:num+=int(''.join(stack))\n",
    "                return coef,num\n",
    "            s1,s2=s.split('=')\n",
    "            c1,n1=parse(s1)\n",
    "            c2,n2=parse(s2)\n",
    "            coef=c1-c2\n",
    "            num=n2-n1\n",
    "            if coef==0:\n",
    "                if num==0:return 'Infinite solutions'\n",
    "                return 'No solution'\n",
    "            return f'x={num//coef}'\n",
    "        return lt640(equation)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        # 考虑到方程里只有加减，将x=0代入，得到常数项的和；x=1代入，得到常数项+x的个数的和\n",
    "        equ = equation.split('=')\n",
    "        # 这里在前面增添一个+是考虑到以x为开头的情况;替换成*0或者*1是删掉x项或者把系数提出来\n",
    "        left_num = eval(('+'+equ[0]).replace('x','*0').replace('+*','+').replace('-*','-'))\n",
    "        left_x = eval(('+'+equ[0]).replace('x','*1').replace('+*','+').replace('-*','-')) - left_num\n",
    "\n",
    "        right_num = eval(('+'+equ[1]).replace('x','*0').replace('+*','+').replace('-*','-'))\n",
    "        right_x = eval(('+'+equ[1]).replace('x','*1').replace('+*','+').replace('-*','-')) - right_num\n",
    "\n",
    "        if left_x == right_x:\n",
    "            if left_num == right_num:\n",
    "                return 'Infinite solutions'\n",
    "            else:\n",
    "                return 'No solution'\n",
    "        return 'x='+str((right_num - left_num) // (left_x - right_x))\n",
    "        \n",
    "\n",
    "if __name__ == '__main__':\n",
    "    equation = \"x+5-3+x=6+x-2\"\n",
    "    sol = Solution()\n",
    "    print(sol.solveEquation(equation))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        n1 = 0\n",
    "        n = len(equation)\n",
    "        s = equation + '+'\n",
    "        n2 = 0  # 记录x的系数\n",
    "        n3 = 0  # 记录常数\n",
    "        f1 = 1  # 符号位\n",
    "        f2 = 1 \n",
    "        for i in range(n + 1):\n",
    "            if s[i] == '-':\n",
    "                if n1 != 0:\n",
    "                    n3 += f1 * n1 * (-f2)\n",
    "                f1 = -1\n",
    "                n1 = 0\n",
    "            elif s[i] == '+':\n",
    "                if n1 != 0:\n",
    "                    n3 += f1 * n1 * (-f2)\n",
    "                f1 = 1\n",
    "                n1 = 0\n",
    "            elif s[i] == '=':\n",
    "                if n1 != 0:\n",
    "                    n3 += f1 * n1 * (-f2)\n",
    "                f2 = -1\n",
    "                f1 = 1\n",
    "                n1 = 0\n",
    "            elif s[i] == 'x':\n",
    "                if i > 0 and s[i - 1] == '0' and n1 == 0:\n",
    "                    n1 = 0\n",
    "                else:\n",
    "                    n1 = max(n1, 1)\n",
    "                n2 += f1 * f2 * n1\n",
    "                n1 = 0\n",
    "            else:\n",
    "                n1 = n1 * 10 + int(s[i])\n",
    "        print(n2, n3)\n",
    "        if n2 == 0 and n3 == 0:\n",
    "            return 'Infinite solutions'\n",
    "        elif n2 == 0:\n",
    "            return 'No solution'\n",
    "        else:\n",
    "            return f\"x={n3 // n2}\"\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "\n",
    "def fc2(string):\n",
    "    lst2 = []\n",
    "    if string[0] not in ['-','+']:\n",
    "        string = '+'+string\n",
    "    idx = string.index('=')\n",
    "    if string[idx+1] not in ['-','+']:\n",
    "        string = string.replace('=','=+')\n",
    "    for s in string:\n",
    "        if s in ['-','+','=']:\n",
    "            lst2.append(s)\n",
    "    # print('string',string)\n",
    "    string = string.replace('=+','_').replace('=-','_').replace('-','_').replace('+','_')\n",
    "    return string.split('_')[1:],lst2\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        lst1,lst2 = fc2(equation)\n",
    "        # print('lst1',lst1)\n",
    "        # print('lst2',lst2)\n",
    "        n = len(lst1)\n",
    "        x_num = 0\n",
    "        left = 0\n",
    "        right = 0\n",
    "        i,j=0,0\n",
    "        for _ in range(n):\n",
    "            s = lst1[i]\n",
    "            fh = lst2[j]\n",
    "            if fh=='=':\n",
    "                j+=1\n",
    "                fh = lst2[j]\n",
    "                right = -left\n",
    "            if i==j:\n",
    "                if 'x' in s:\n",
    "                    if len(s)==1:\n",
    "                        s = '1'+s\n",
    "                    x_num = eval('{}{}{}'.format(x_num,fh,s[:-1]))\n",
    "                else:\n",
    "                    left = eval('{}{}{}'.format(left,fh,s))\n",
    "                # print('i=j',x_num,left)\n",
    "            else:\n",
    "                if 'x' in s:\n",
    "                    if len(s)==1:\n",
    "                        s = '1'+s\n",
    "                    x_num = eval('{}-({}{})'.format(x_num,fh,s[:-1]))\n",
    "                else:\n",
    "                    right = eval('{}{}{}'.format(right,fh,s))\n",
    "                # print('i!=j',x_num,right)\n",
    "            i+=1\n",
    "            j+=1\n",
    "        # print('{}x={}'.format(x_num,right))\n",
    "        if x_num==0:\n",
    "            if right==0:\n",
    "                return 'Infinite solutions'\n",
    "            else:\n",
    "                return 'No solution'\n",
    "        elif right%x_num:\n",
    "            return 'No solution'\n",
    "        else:\n",
    "            return 'x={}'.format(right//x_num)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        n = len(equation)\n",
    "        x = c = i = 0\n",
    "        while i < n:\n",
    "            if equation[i] == \"=\":\n",
    "                x *= -1\n",
    "                c *= -1\n",
    "                i += 1\n",
    "                continue\n",
    "            signal = 1\n",
    "            if equation[i] == \"+\":\n",
    "                i += 1\n",
    "            elif equation[i] == \"-\":\n",
    "                signal = -1\n",
    "                i += 1\n",
    "\n",
    "            num = 0\n",
    "            digit = False\n",
    "            while i < n and equation[i].isdigit():\n",
    "                digit = True\n",
    "                num = num * 10 + int(equation[i])\n",
    "                i += 1\n",
    "            if i<n and equation[i] == \"x\":\n",
    "                x += signal * (num if digit else 1)\n",
    "                i += 1\n",
    "            else:\n",
    "                c += signal * num\n",
    "\n",
    "        if x == 0:\n",
    "            return \"No solution\" if c else \"Infinite solutions\"\n",
    "\n",
    "        return f\"x={-c//x}\"\n",
    "\n",
    "            \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "\r\n",
    "class Solution:\r\n",
    "    def solveEquation(self, equation: str) -> str:\r\n",
    "        # sign: 当前正负, cur: 当前数字, num: 等式的数字项大小, k: 等式x的系数, left: 是否在等号左, has_val: 当前有没有出现任何数字\r\n",
    "        sign, cur, num, k, left, has_val = 1, 0, 0, 0, True, False\r\n",
    "        for c in equation + \"=\":\r\n",
    "            if c in \"-+=x\":\r\n",
    "                if c == 'x':\r\n",
    "                    if not has_val and not cur:\r\n",
    "                        cur = 1\r\n",
    "                    k += sign * cur if left else -sign * cur\r\n",
    "                else:\r\n",
    "                    num += sign * cur if not left else -sign * cur\r\n",
    "                cur, has_val = 0, False\r\n",
    "            match c:\r\n",
    "                case \"-\":\r\n",
    "                    sign = -1\r\n",
    "                case \"+\":\r\n",
    "                    sign = 1\r\n",
    "                case \"=\":\r\n",
    "                    sign, left = 1, False\r\n",
    "                case \"x\":\r\n",
    "                    pass\r\n",
    "                case _:\r\n",
    "                    cur, has_val = cur * 10 + int(c), True\r\n",
    "        if not k:\r\n",
    "            return \"No solution\" if num else \"Infinite solutions\"\r\n",
    "        return f\"x={num//k}\" if not (num % k) else \"No solution\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        equation = equation+'+'\n",
    "        stack = []\n",
    "        re = 1\n",
    "        flag = 1\n",
    "        xcoeff = 0\n",
    "        stack = []\n",
    "        res = 0\n",
    "        for i,ich in enumerate(equation):\n",
    "            if ich.isspace():\n",
    "                continue\n",
    "            if ich.isdigit():\n",
    "                stack.append(eval(ich))\n",
    "                continue\n",
    "            if ich=='+' or ich=='-' or ich=='=':\n",
    "                if len(stack)>0:\n",
    "                    a = stack.pop()\n",
    "                    if a=='x':\n",
    "                        k = 0\n",
    "                        tmpcoef = 0\n",
    "                        if len(stack)==0:\n",
    "                            tmpcoef=1\n",
    "                        while len(stack)>0:\n",
    "                            tmpcoef = tmpcoef+stack.pop()*10**k\n",
    "                            k = k+1\n",
    "                        xcoeff = xcoeff + flag*re*tmpcoef\n",
    "                        \n",
    "                    else:\n",
    "                        tmpr = a\n",
    "                        k = 1\n",
    "                        while len(stack)>0:\n",
    "                            tmpr = tmpr+stack.pop()*10**k\n",
    "                            k = k+1\n",
    " \n",
    "                        res = res+tmpr*flag*re\n",
    "                if ich=='+':\n",
    "                    flag=1\n",
    "                elif ich=='-':\n",
    "                    flag=-1\n",
    "                else:\n",
    "                    flag = 1\n",
    "                    re = -1\n",
    "                continue\n",
    "            if ich == 'x':\n",
    "                stack.append(ich)\n",
    "                continue\n",
    "        if xcoeff == 0 and res==0:\n",
    "            return \"Infinite solutions\"\n",
    "        if xcoeff == 0:\n",
    "            return \"No solution\"\n",
    "        return \"x=\"+str(int(-res/xcoeff))\n",
    "                        \n",
    "                \n",
    "            \n",
    "            \n",
    "            \n",
    "            \n",
    "            \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "\tdef solveEquation(self, eq):\n",
    "\t\ts = eq.split('=')\n",
    "\t\ta = [[0, 0], [0, 0]]\n",
    "\t\tfor i, s in enumerate(eq.split('=')):\n",
    "\t\t\tsign, num = 1, None\n",
    "\t\t\tfor c in s + '+':\n",
    "\t\t\t\tif c in '+-':\n",
    "\t\t\t\t\tif num is not None:\n",
    "\t\t\t\t\t\ta[i][1] += num * sign\n",
    "\t\t\t\t\tsign = 1 if c == '+' else -1\n",
    "\t\t\t\t\tnum = None\n",
    "\t\t\t\telif c == 'x':\n",
    "\t\t\t\t\ta[i][0] += 1 * sign if num is None else num * sign\n",
    "\t\t\t\t\tnum = None\n",
    "\t\t\t\telif c in '0123456789':\n",
    "\t\t\t\t\tnum = (0 if num is None else num) * 10 + int(c)\n",
    "\t\tx, y = a[0][0] - a[1][0], a[1][1] - a[0][1]\n",
    "\t\tif x == 0:\n",
    "\t\t\treturn \"Infinite solutions\" if y == 0 else \"No solution\"\n",
    "\t\telse:\n",
    "\t\t\treturn f\"x={y // x}\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        flag = 1\n",
    "        n = len(equation)\n",
    "        num, num_x, num_int, sign = 0, 0, 0, 1\n",
    "        i = 0\n",
    "        while i < n:\n",
    "            if equation[i] == '-':\n",
    "                sign = -1\n",
    "                i += 1\n",
    "            elif equation[i] == '+':\n",
    "                sign = 1\n",
    "                i += 1\n",
    "            while i < n and equation[i].isdigit():\n",
    "                num = 10 *num + int(equation[i])\n",
    "                i += 1\n",
    "\n",
    "            if i == n or equation[i] != 'x':\n",
    "                num_int += flag * num * sign\n",
    "                num = 0\n",
    "            else:\n",
    "                if num == 0 and equation[i-1] != '0' or i == 0:\n",
    "                    num = 1 \n",
    "                num_x += flag * num * sign\n",
    "                num = 0\n",
    "                i += 1\n",
    "            \n",
    "            if i < n and equation[i] == '=':\n",
    "                flag = -1\n",
    "                sign = 1\n",
    "                i += 1\n",
    "                \n",
    "        if num_x == 0 and num_int != 0:\n",
    "            return \"No solution\"\n",
    "        elif num_x == 0:\n",
    "            return \"Infinite solutions\"\n",
    "\n",
    "        return f'x={int(-num_int/ num_x)}'\n",
    "            \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        sign = 1 \n",
    "        left_x_coefficient = 0\n",
    "        right_constant = 0\n",
    "        equation_length = len(equation)\n",
    "        index = 0 \n",
    "        temp_sign = 1\n",
    "        while index < equation_length:\n",
    "            if equation[index] == '=':\n",
    "                sign *= -1\n",
    "                index += 1\n",
    "            elif equation[index] == '+':\n",
    "                index += 1\n",
    "            elif equation[index] == '-':\n",
    "                temp_sign = -1\n",
    "                index += 1\n",
    "            elif equation[index] == 'x':\n",
    "                left_x_coefficient += (temp_sign * sign) \n",
    "                index += 1 \n",
    "                temp_sign = 1\n",
    "            else:\n",
    "                end_index = index + 1\n",
    "                while end_index < equation_length:\n",
    "                    if equation[end_index] != '+' and equation[end_index] != '-' and equation[end_index] != '=':\n",
    "                        end_index += 1\n",
    "                    else:\n",
    "                        break \n",
    "                if equation[index:end_index].isdigit():\n",
    "                    right_constant += (1 * temp_sign) * (-1 * sign) * (int(equation[index:end_index]))\n",
    "                else:\n",
    "                    left_x_coefficient += temp_sign * sign * (int(equation[index:end_index - 1]))\n",
    "                index = end_index\n",
    "                temp_sign = 1\n",
    "        if left_x_coefficient:\n",
    "            return 'x=' + str(right_constant // left_x_coefficient)\n",
    "        else:\n",
    "            if right_constant:\n",
    "                return 'No solution'\n",
    "            else:\n",
    "                return 'Infinite solutions'\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        n = len(equation)\n",
    "        a, b = 0, 0\n",
    "        i, sign = 0, 1\n",
    "        while i < n:\n",
    "            if equation[i] == '=':\n",
    "                sign = -1\n",
    "                i += 1\n",
    "                continue\n",
    "            \n",
    "            s = sign\n",
    "            if equation[i] == '+':\n",
    "                i += 1\n",
    "            elif equation[i] == '-':\n",
    "                s = -s\n",
    "                i += 1\n",
    "            \n",
    "            num, valid = 0, False\n",
    "            while i < n and equation[i].isdigit():\n",
    "                valid = True\n",
    "                num = num * 10 + int(equation[i])\n",
    "                i += 1\n",
    "            if i < n and equation[i] == 'x':\n",
    "                a += s * num if valid else s\n",
    "                i += 1\n",
    "            else:\n",
    "                b += s * num\n",
    "        if a == 0: \n",
    "            return \"No solution\" if b else \"Infinite solutions\"\n",
    "            \n",
    "        return f\"x={-b // a}\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        # sign: 当前正负, cur: 当前数字, num: 等式的数字项大小, k: 等式x的系数, left: 是否在等号左, has_val: 当前有没有出现任何数字\n",
    "        sign, cur, num, k, left, has_val = 1, 0, 0, 0, True, False\n",
    "        for c in equation + \"=\":\n",
    "            if c in \"-+=x\":\n",
    "                if c == 'x':\n",
    "                    if not has_val and not cur:\n",
    "                        cur = 1\n",
    "                    k += sign * cur if left else -sign * cur\n",
    "                else:\n",
    "                    num += sign * cur if not left else -sign * cur\n",
    "                cur, has_val = 0, False\n",
    "            match c:\n",
    "                case \"-\":\n",
    "                    sign = -1\n",
    "                case \"+\":\n",
    "                    sign = 1\n",
    "                case \"=\":\n",
    "                    sign, left = 1, False\n",
    "                case \"x\":\n",
    "                    pass\n",
    "                case _:\n",
    "                    cur, has_val = cur * 10 + int(c), True\n",
    "        if not k:\n",
    "            return \"No solution\" if num else \"Infinite solutions\"\n",
    "        return f\"x={num//k}\" if not (num % k) else \"No solution\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str: \n",
    "        lx = []\n",
    "        lnum = []\n",
    "        rx = []\n",
    "        rnum = []\n",
    "        num = [str(i) for i in range(10)]\n",
    "        tmpnum = -1\n",
    "        pos = 1\n",
    "        lflag = 0\n",
    "        xflag = 0\n",
    "        for i in equation:\n",
    "            if not lflag:\n",
    "                if i in num:\n",
    "                    if tmpnum == -1:\n",
    "                        tmpnum = int(i)\n",
    "                    else: \n",
    "                        tmpnum = tmpnum * 10 + int(i)\n",
    "                elif i == 'x':\n",
    "                    xflag = 1\n",
    "                elif i == '+':\n",
    "                    if xflag:\n",
    "                        if tmpnum != -1:\n",
    "                            lx.append(tmpnum * pos)\n",
    "                        else:\n",
    "                            lx.append(1 * pos)\n",
    "                    elif tmpnum != -1:\n",
    "                        lnum.append(tmpnum * pos)\n",
    "                    tmpnum = -1\n",
    "                    xflag = 0\n",
    "                    pos = 1\n",
    "                elif i == '-':\n",
    "                    if xflag:\n",
    "                        if tmpnum != -1:\n",
    "                            lx.append(tmpnum * pos)\n",
    "                        else:\n",
    "                            lx.append(1 * pos)\n",
    "                    elif tmpnum != -1:\n",
    "                        lnum.append(tmpnum * pos)\n",
    "                    tmpnum = -1\n",
    "                    xflag = 0\n",
    "                    pos = -1\n",
    "                elif i == '=':\n",
    "                    lflag = 1\n",
    "                    if xflag:\n",
    "                        if tmpnum != -1:\n",
    "                            lx.append(tmpnum * pos)\n",
    "                        else:\n",
    "                            lx.append(1 * pos)\n",
    "                    elif tmpnum != -1:\n",
    "                        lnum.append(tmpnum * pos)\n",
    "                    tmpnum = -1\n",
    "                    xflag = 0\n",
    "                    pos = 1\n",
    "            elif lflag:\n",
    "                if i in num:\n",
    "                    if tmpnum == -1:\n",
    "                        tmpnum = int(i)\n",
    "                    else: \n",
    "                        tmpnum = tmpnum * 10 + int(i)\n",
    "                elif i == 'x':\n",
    "                    xflag = 1\n",
    "                elif i == '+':\n",
    "                    if xflag:\n",
    "                        if tmpnum != -1:\n",
    "                            rx.append(tmpnum * pos)\n",
    "                        else:\n",
    "                            rx.append(1 * pos)\n",
    "                    elif tmpnum != -1:\n",
    "                        rnum.append(tmpnum * pos)\n",
    "                    tmpnum = -1\n",
    "                    xflag = 0\n",
    "                    pos = 1\n",
    "                elif i == '-':\n",
    "                    if xflag:\n",
    "                        if tmpnum != -1:\n",
    "                            rx.append(tmpnum * pos)\n",
    "                        else:\n",
    "                            rx.append(1 * pos)\n",
    "                    elif tmpnum != -1:\n",
    "                        rnum.append(tmpnum * pos)\n",
    "                    tmpnum = -1\n",
    "                    xflag = 0\n",
    "                    pos = -1\n",
    "        if xflag:\n",
    "            if tmpnum != -1:\n",
    "                rx.append(tmpnum * pos)\n",
    "            else:\n",
    "                rx.append(1 * pos)\n",
    "        elif tmpnum != -1:\n",
    "            rnum.append(tmpnum * pos)    \n",
    "            \n",
    "        print(lx, lnum, rx, rnum)\n",
    "        x = sum(lx) - sum(rx)\n",
    "        n = sum(rnum) - sum(lnum)\n",
    "        if x == 0 and n == 0:\n",
    "            return \"Infinite solutions\"\n",
    "        elif x == 0 and n != 0:\n",
    "            return \"No solution\"\n",
    "        else:\n",
    "            return \"x=\" + str(n//x)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        factor = val = 0\n",
    "        i, n, sign = 0, len(equation), 1  # 等式左边默认系数为正\n",
    "        while i < n:\n",
    "            if equation[i] == '=':\n",
    "                sign = -1\n",
    "                i += 1\n",
    "                continue\n",
    "\n",
    "            s = sign\n",
    "            if equation[i] == '+':  # 去掉前面的符号\n",
    "                i += 1\n",
    "            elif equation[i] == '-':\n",
    "                s = -s\n",
    "                i += 1\n",
    "\n",
    "            num, valid = 0, False\n",
    "            while i < n and equation[i].isdigit():\n",
    "                valid = True\n",
    "                num = num * 10 + int(equation[i])\n",
    "                i += 1\n",
    "\n",
    "            if i < n and equation[i] == 'x':  # 变量\n",
    "                factor += s * num if valid else s\n",
    "                i += 1\n",
    "            else:  # 数值\n",
    "                val += s * num\n",
    "\n",
    "        if factor == 0:\n",
    "            return \"No solution\" if val else \"Infinite solutions\"\n",
    "        return f\"x={-val // factor}\"\n",
    "\n",
    " "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        #Lcheck=0\n",
    "        #Rcheck=0\n",
    "        counta=0\n",
    "        countb=0\n",
    "        numbera=0\n",
    "        numberb=0\n",
    "        equation2=equation.split('=')\n",
    "        \n",
    "        first=equation2[0]\n",
    "        second=equation2[1]\n",
    "\n",
    "        if first[0]!='-':\n",
    "            first='+'+first\n",
    "        if second[0]!='-':\n",
    "            second='+'+second\n",
    "        \n",
    "        signalA=[]\n",
    "        contentA=[]\n",
    "        signalB=[]\n",
    "        contentB=[]\n",
    "\n",
    "        temp=''\n",
    "        for i,j in enumerate(first):\n",
    "            if j=='+' or j=='-':\n",
    "                signalA.append(j)\n",
    "                contentA.append(temp)\n",
    "                temp=''\n",
    "            else:\n",
    "                temp+=j\n",
    "                \n",
    "            \n",
    "            if i==len(first)-1:\n",
    "                contentA.append(temp)\n",
    "        \n",
    "        for i,j in enumerate(second):\n",
    "            if j=='+' or j=='-' :\n",
    "                signalB.append(j)\n",
    "                contentB.append(temp)\n",
    "                temp=''\n",
    "            else:\n",
    "                temp+=j\n",
    "                \n",
    "            \n",
    "            if i==len(second)-1:\n",
    "                contentB.append(temp)\n",
    "        \n",
    "        \n",
    "        contentA.pop(0)\n",
    "        contentB.pop(0)\n",
    "        #return contentA\n",
    "        for i in range(len(contentA)):\n",
    "            if signalA[i]=='+':\n",
    "                if 'x' not in contentA[i]:\n",
    "                    numbera+=int(contentA[i])\n",
    "                    #Lcheck=1\n",
    "                else:\n",
    "                    if len(contentA[i])==1:\n",
    "                        counta+=1\n",
    "                    else:\n",
    "                        zz=contentA[i][:-1]\n",
    "                        counta+=int(zz)\n",
    "            else:\n",
    "                if 'x' not in contentA[i]:\n",
    "                    numbera-=int(contentA[i])\n",
    "                    #Lcheck=1\n",
    "                else:\n",
    "                    if len(contentA[i])==1:\n",
    "                        counta-=1\n",
    "                    else:\n",
    "                        zz=contentA[i][:-1]\n",
    "                        counta-=int(zz)\n",
    "        \n",
    "        for i in range(len(contentB)):\n",
    "            if signalB[i]=='+':\n",
    "                if 'x' not in contentB[i]:\n",
    "                    numberb+=int(contentB[i])\n",
    "                    #Rcheck=1\n",
    "                else:\n",
    "                    if len(contentB[i])==1:\n",
    "                        countb+=1\n",
    "                    else:\n",
    "                        zz=contentB[i][:-1]\n",
    "                        countb+=int(zz)\n",
    "            else:\n",
    "                if 'x' not in contentB[i]:\n",
    "                    numberb-=int(contentB[i])\n",
    "                    #Rcheck=1\n",
    "                else:\n",
    "                    if len(contentB[i])==1:\n",
    "                        countb-=1\n",
    "                    else:\n",
    "                        zz=contentB[i][:-1]\n",
    "                        countb-=int(zz)\n",
    "        \n",
    "        #if Lcheck==0 and Rcheck==0:\n",
    "        if counta==countb and numbera==numberb:\n",
    "            return 'Infinite solutions'\n",
    "        elif counta!=countb and numberb==numbera : \n",
    "            return 'x=0'      \n",
    "        elif counta==countb and numbera!=numberb:\n",
    "            return 'No solution'\n",
    "        \n",
    "        #return counta,numbera,countb,numberb\n",
    "        numberb-=numbera\n",
    "        counta-=countb\n",
    "\n",
    "        \n",
    "\n",
    "\n",
    "        ans=str(int(numberb/counta))\n",
    "        return 'x='+ans\n",
    "\n",
    "\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        l = [0] * 2\n",
    "        r = [0] * 2\n",
    "        a, b = equation.split('=')\n",
    "        i, sign = 0, 1\n",
    "        while i < len(a):\n",
    "            if a[i] == '+' or a[i] == '-':#符号\n",
    "                if a[i] == '-':\n",
    "                    sign = -1\n",
    "                else:\n",
    "                    sign = 1\n",
    "                i += 1\n",
    "            temp = 0\n",
    "            have_temp = 0\n",
    "            while i < len(a) and a[i] != '+' and a[i] != '-' and a[i] != 'x':\n",
    "                temp = temp * 10 + int(a[i])\n",
    "                have_temp = 1\n",
    "                i += 1# 找数字\n",
    "            if i <len(a):\n",
    "                if a[i] == 'x':\n",
    "                    i += 1\n",
    "                    if have_temp == 0:\n",
    "                        temp = 1\n",
    "                    l[0] += temp * sign\n",
    "                else:\n",
    "                    l[1] += temp * sign\n",
    "            else:\n",
    "                l[1] += temp * sign\n",
    "        print(l)\n",
    "        i = 0\n",
    "        sign = 1\n",
    "        while i < len(b):\n",
    "            if b[i] == '+' or b[i] == '-':#符号\n",
    "                if b[i] == '-':\n",
    "                    sign = -1\n",
    "                else:\n",
    "                    sign = 1\n",
    "                i += 1\n",
    "            temp = 0\n",
    "            have_temp = 0\n",
    "            while i < len(b) and b[i] != '+' and b[i] != '-' and b[i] != 'x':\n",
    "                temp = temp * 10 + int(b[i])\n",
    "                have_temp = 1\n",
    "                i += 1# 找数字\n",
    "            if i <len(b):\n",
    "                if b[i] == 'x':\n",
    "                    i += 1\n",
    "                    if have_temp == 0:\n",
    "                        temp = 1\n",
    "                    r[0] += temp * sign\n",
    "                else:\n",
    "                    r[1] += temp * sign\n",
    "            else:\n",
    "                r[1] += temp * sign\n",
    "        print(r)\n",
    "        #No solution: 无解 或 解非整数\n",
    "        res = [0] * 2\n",
    "        res[0] = l[0] - r[0]\n",
    "        res[1] = r[1] - l[1]# 0 为变量 1 为 数字\n",
    "        if res[0] == 0 and res[1] == 0:\n",
    "            return \"Infinite solutions\"\n",
    "        if res[0] != 0 and res[1] != 0:\n",
    "            temp = res[1] / res[0]\n",
    "            if temp % 1 == 0:\n",
    "                return \"x={}\".format(int(temp))\n",
    "            else:\n",
    "                return \"No solution\"\n",
    "        if res[0] != 0 and res[1] == 0:\n",
    "            return \"x=0\"\n",
    "        if res[0] == 0 and res[1] != 0:\n",
    "            return \"No solution\"\n",
    "\n",
    "\n",
    "            \n",
    "            \n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        n = len(equation)\n",
    "        i = 0\n",
    "        sign = 1\n",
    "        factor,val = 0,0\n",
    "        while i < n:\n",
    "            if equation[i] == \"=\":\n",
    "                sign = -1\n",
    "                i += 1\n",
    "                continue\n",
    "            s = sign\n",
    "            if equation[i] == \"+\":\n",
    "                i += 1\n",
    "            if equation[i] == \"-\":\n",
    "                s *= -1\n",
    "                i += 1\n",
    " \n",
    "\n",
    "            value = False\n",
    "            num = 0\n",
    "            while i < n and equation[i].isdigit():\n",
    "                value = True\n",
    "                num = num*10 + int(equation[i])\n",
    "                i += 1 \n",
    "\n",
    "            if i < n and equation[i] == \"x\":\n",
    "                factor += num*s if value else s \n",
    "                i += 1\n",
    "            else:\n",
    "                val += num*s \n",
    "        \n",
    "        if factor == 0 and val == 0:\n",
    "            return \"Infinite solutions\"\n",
    "        if factor == 0 and val != 0:\n",
    "            return \"No solution\"\n",
    "        print(factor)\n",
    "        print(val)\n",
    "        return f\"x={-val//factor}\" \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        equation = equation.replace('-','+-')\n",
    "        strl,strr = equation.split(\"=\")\n",
    "        ll = strl.split(\"+\")\n",
    "        lr = strr.split(\"+\")\n",
    "        cntl = 0\n",
    "        cntlx = 0\n",
    "        cntr = 0\n",
    "        cntrx = 0\n",
    "        for i in ll:\n",
    "            if i.find(\"x\")>=0:\n",
    "                if i==\"x\":\n",
    "                    cntlx+=1\n",
    "                elif i==\"-x\":\n",
    "                    cntlx-=1\n",
    "                else:\n",
    "                    i = i.replace(\"x\",'')\n",
    "                    cntlx+=int(i)\n",
    "            else:\n",
    "                if i!='':\n",
    "                    cntl+=int(i)\n",
    "        for j in lr:\n",
    "            if j.find(\"x\")>=0:\n",
    "                if j==\"x\":\n",
    "                    cntrx+=1\n",
    "                elif j==\"-x\":\n",
    "                    cntrx-=1\n",
    "                else:\n",
    "                    j = j.replace(\"x\",'')\n",
    "                    cntrx+=int(j)\n",
    "            else:\n",
    "                if j!='':\n",
    "                    cntr+=int(j)\n",
    "        print(cntl,cntlx,cntr,cntrx)\n",
    "        if cntlx == cntrx:\n",
    "            if cntl == cntr:\n",
    "                return \"Infinite solutions\"\n",
    "            else:\n",
    "                return \"No solution\"\n",
    "        if cntl ==cntr:\n",
    "            return \"x=0\"\n",
    "        else:\n",
    "            if (cntr-cntl)/(cntlx-cntrx) == int((cntr-cntl)/(cntlx-cntrx)):\n",
    "                return \"x=\"+str(int((cntr-cntl)/(cntlx-cntrx)))\n",
    "            else:\n",
    "                return \"No solution\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        def get_part(ans, part, flag):\n",
    "            for part in part.split('+'):\n",
    "                if not part:\n",
    "                    continue\n",
    "                if part[-1] == 'x':\n",
    "                    if len(part) == 1:\n",
    "                        ans[1] += flag\n",
    "                    elif len(part) == 2 and part[0] == '-':\n",
    "                        ans[1] += -flag\n",
    "                    else:\n",
    "                        ans[1] += flag * int(part[:-1])\n",
    "                else:\n",
    "                    ans[0] += flag * int(part)\n",
    "        equation = equation.replace('-', '+-')\n",
    "        left, right = equation.split('=')\n",
    "        ans = [0, 0]\n",
    "        get_part(ans, left, 1)\n",
    "        get_part(ans, right, -1)\n",
    "        \n",
    "        if ans[1] == 0:\n",
    "            if ans[0] == 0:\n",
    "                return \"Infinite solutions\"\n",
    "            else:\n",
    "                return \"No solution\"\n",
    "        return f\"x={-1*ans[0] // ans[1]}\"\n",
    "        \n",
    "    \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        tmp=\"\"\n",
    "        n=len(equation)\n",
    "        sign=1\n",
    "        last=1\n",
    "        stack=[]\n",
    "        xside=0\n",
    "        nside=0\n",
    "        i=0\n",
    "        while i <n:\n",
    "            kk=equation[i]\n",
    "           # if kk==\"=\":\n",
    "             ##   sign=-1\n",
    "              #  i=i+1\n",
    "              #  continue\n",
    "            #print(stack)\n",
    "            if kk in [\"+\",\"-\",\"=\"]:\n",
    "                if len(stack)==0:\n",
    "                    stack=[]\n",
    "                elif stack[-1]==\"x\":\n",
    "                    if len(stack)==1:\n",
    "                        xside=xside+last*sign*1\n",
    "                    else:\n",
    "                        xside=xside+last*sign*int(\"\".join(stack[:-1]))\n",
    "                else:\n",
    "                    #print(stack)\n",
    "                    nside=nside+last*sign*int(\"\".join(stack))\n",
    "                if kk==\"+\":\n",
    "                    last=1\n",
    "                elif kk==\"-\":\n",
    "                    last=-1\n",
    "                elif kk==\"=\":\n",
    "                    sign=-1\n",
    "                    last=1\n",
    "                #print(stack,nside,xside,sign)\n",
    "                stack=[]\n",
    "\n",
    "            else:\n",
    "                stack.append(kk)\n",
    "            i=i+1\n",
    "        \n",
    "        if len(stack)!=0:\n",
    "            if stack[-1]==\"x\":\n",
    "                if len(stack)==1:\n",
    "                    xside=xside+last*sign*1\n",
    "                else:\n",
    "                    xside=xside+last*sign*int(\"\".join(stack[:-1]))\n",
    "            else:\n",
    "                    #print(stack)\n",
    "                nside=nside+last*sign*int(\"\".join(stack))\n",
    "\n",
    "        print(nside,xside)\n",
    "        if xside==0 and nside!=0:\n",
    "            return \"No solution\"\n",
    "        elif  xside==0 and nside==0:\n",
    "            return \"Infinite solutions\"\n",
    "        else:\n",
    "            return \"x=\"+str(-nside//xside)\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "            \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        equation = equation.split('=')\n",
    "        left, right = equation[0], equation[1]\n",
    "\n",
    "        def convert(s):\n",
    "            k, value = 0, 0\n",
    "            st = 0\n",
    "            n = len(s)\n",
    "            for i in range(n):\n",
    "                if (s[i] == '-' or s[i] == '+') and st != i:\n",
    "                    value += int(s[st:i])\n",
    "                    st = i\n",
    "                elif s[i] == 'x':\n",
    "                    if i > st + 1:\n",
    "                        k += int(s[st:i])\n",
    "                    else:\n",
    "                        if s[st] == '+' or s[st] == 'x':\n",
    "                            k += 1\n",
    "                        elif s[st] == '-':\n",
    "                            k -= 1\n",
    "                        else:\n",
    "                            k += int(s[st])\n",
    "                    st = i + 1\n",
    "            if st < n: value += int(s[st:])\n",
    "            return k, value\n",
    "\n",
    "        l_k, l_value = convert(left)\n",
    "        r_k, r_value = convert(right)\n",
    "        if l_k == r_k:\n",
    "            if l_value == r_value:\n",
    "                return 'Infinite solutions'\n",
    "            else:\n",
    "                return 'No solution'\n",
    "        else:\n",
    "            return f'x={(r_value - l_value) // (l_k - r_k)}'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        res: complex = eval(\n",
    "            (\"0+\" + equation.replace(\"x\", \"j\"))\n",
    "                .replace(\"=\", \"-(\") \n",
    "                .replace(\"+j\", \"+1j\")\n",
    "                .replace(\"-j\", \"-1j\")\n",
    "                .replace(\"(j\", \"(1j\")\n",
    "                + \")\"\n",
    "                \n",
    "        )\n",
    "        if res == 0:\n",
    "            return \"Infinite solutions\"\n",
    "        return f\"x={-int(res.real / res.imag)}\" if res.imag != 0 else \"No solution\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        def check(st):\n",
    "            a = b = i = 0\n",
    "            m = len(st)\n",
    "            while i < m:\n",
    "                cur = st[i]\n",
    "                while i + 1 < m and st[i + 1] not in \"+-\":\n",
    "                    cur += st[i + 1]\n",
    "                    i += 1\n",
    "                # 更新系数\n",
    "                if cur[-1] == \"x\":\n",
    "                    cur = cur[:-1]\n",
    "                    # 注意\"+x\"\\\"-x\"\\\"x\"的特殊情况\n",
    "                    a += int(cur) if cur and cur not in \"+-\" else int(cur + \"1\")\n",
    "                else:\n",
    "                    b += int(cur)\n",
    "                i += 1\n",
    "            return [a, b]\n",
    "\n",
    "        lst = equation.split(\"=\")\n",
    "        a1, b1 = check(lst[0])\n",
    "        a2, b2 = check(lst[1])\n",
    "        if a1 == a2:\n",
    "            return \"Infinite solutions\" if b1 == b2 else \"No solution\"\n",
    "        ans = (b2 - b1) // (a1 - a2)\n",
    "        return f\"x={ans}\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        factor = val = 0\n",
    "        i, n, sign = 0, len(equation), 1  # 等式左边默认系数为正\n",
    "        while i < n:\n",
    "            if equation[i] == '=':\n",
    "                sign = -1\n",
    "                i += 1\n",
    "                continue\n",
    "\n",
    "            s = sign\n",
    "            if equation[i] == '+':  # 去掉前面的符号\n",
    "                i += 1\n",
    "            elif equation[i] == '-':\n",
    "                s = -s\n",
    "                i += 1\n",
    "\n",
    "            num, valid = 0, False\n",
    "            while i < n and equation[i].isdigit():\n",
    "                valid = True\n",
    "                num = num * 10 + int(equation[i])\n",
    "                i += 1\n",
    "\n",
    "            if i < n and equation[i] == 'x':  # 变量\n",
    "                factor += s * num if valid else s\n",
    "                i += 1\n",
    "            else:  # 数值\n",
    "                val += s * num\n",
    "\n",
    "        if factor == 0:\n",
    "            return \"No solution\" if val else \"Infinite solutions\"\n",
    "        return f\"x={-val // factor}\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        # 分部计算\n",
    "        def get_part(ans, part, flag):\n",
    "            for p in part.split('+'):\n",
    "                print(p)\n",
    "                if not p:\n",
    "                    continue\n",
    "                if p[-1] == 'x':\n",
    "                    if len(p) == 1:\n",
    "                        ans[1] += flag\n",
    "                    elif len(p) == 2 and p[0] == '-':\n",
    "                        ans[1] += -flag\n",
    "                    else:\n",
    "                        ans[1] += flag * int(p[:-1])\n",
    "                else:\n",
    "                    ans[0] += int(p) * flag\n",
    "\n",
    "        #替换- 为 +-\n",
    "        equation = equation.replace('-', '+-')\n",
    "        left, right = equation.split('=')\n",
    "        ans = [0, 0]\n",
    "        get_part(ans, left, 1)\n",
    "        get_part(ans, right, -1)\n",
    "        if ans[1] == 0:\n",
    "            if ans[0] == 0:\n",
    "                return \"Infinite solutions\"\n",
    "            else:\n",
    "                return \"No solution\"\n",
    "        return f'x={-1*ans[0]//ans[1]}'\n",
    "        \n",
    "    \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "# sign: 当前正负, cur: 当前数字, num: 等式的数字项大小, k: 等式x的系数, left: 是否在等号左, has_val: 当前有没有出现任何数字\n",
    "        sign, cur, num, k, left, has_val = 1, 0, 0, 0, True, False\n",
    "        for c in equation + \"=\":\n",
    "            if c in \"-+=x\":\n",
    "                if c == 'x':\n",
    "                    if not has_val and not cur:\n",
    "                        cur = 1\n",
    "                    if left:\n",
    "                        k += sign * cur\n",
    "                    else:\n",
    "                        k += -sign * cur\n",
    "                else:\n",
    "                    if not left:\n",
    "                        num += sign * cur\n",
    "                    else:\n",
    "                        num += -sign * cur\n",
    "                cur, has_val = 0, False\n",
    "            match c:\n",
    "                case \"-\":\n",
    "                    sign = -1\n",
    "                case \"+\":\n",
    "                    sign = 1\n",
    "                case \"=\":\n",
    "                    sign = 1\n",
    "                    left = False\n",
    "                case \"x\":\n",
    "                    pass\n",
    "                case _:\n",
    "                    cur = cur * 10 + int(c)\n",
    "                    has_val = True\n",
    "        if not k:\n",
    "            if num:\n",
    "                return \"No solution\"\n",
    "            else:\n",
    "                return \"Infinite solutions\"\n",
    "        if not (num % k):\n",
    "            return f\"x={num//k}\"\n",
    "        else:\n",
    "            return \"No solution\"\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        left, right = '', ''\n",
    "        i = 0\n",
    "        while equation[i] != '=':\n",
    "            left += equation[i]\n",
    "            i += 1\n",
    "        right = equation[i + 1:]\n",
    "    \n",
    "        left_total, left_var = self.calculate(left)\n",
    "        right_total, right_var = self.calculate(right)\n",
    "        if left_var == right_var:\n",
    "            if left_total == right_total:\n",
    "                return \"Infinite solutions\"\n",
    "            else:\n",
    "                return \"No solution\"\n",
    "        diff_var = left_var - right_var\n",
    "        diff_total = right_total - left_total\n",
    "        if diff_total % diff_var == 0:\n",
    "            return \"x={}\".format(diff_total // diff_var)\n",
    "        return \"No solution\"\n",
    "\n",
    "    def calculate(self, string):\n",
    "        total, num_signs = 0, 0\n",
    "        i = 0\n",
    "        while i < len(string):\n",
    "            sign, tmp = '', ''\n",
    "            if string[i] in ['+', '-']:\n",
    "                sign = string[i]\n",
    "                i += 1\n",
    "            while i < len(string) and '0' <= string[i] <= '9':\n",
    "                if not sign:\n",
    "                    sign = '+'\n",
    "                tmp += string[i] \n",
    "                i += 1\n",
    "            if i < len(string) and string[i] == 'x':\n",
    "                num_signs += self.cal_x(tmp, sign)\n",
    "                i += 1\n",
    "                continue\n",
    "            total += eval(sign + tmp)\n",
    "        return total, num_signs\n",
    "    \n",
    "    def cal_x(self, num, sign):\n",
    "        num_signs = 0\n",
    "        if not num:\n",
    "            num = '1'\n",
    "        if not sign or sign == '+':\n",
    "            num_signs += int(num)\n",
    "        else:\n",
    "            num_signs -= int(num)\n",
    "        return num_signs\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        def get_part(ans, part, flag):\n",
    "            for p in part.split('+'):\n",
    "                if not p:\n",
    "                    continue\n",
    "                if p[-1] == 'x':\n",
    "                    if len(p) == 1:\n",
    "                        ans[1] += flag\n",
    "                    elif len(p) == 2 and p[0] == '-':\n",
    "                        ans[1] += -flag\n",
    "                    else:\n",
    "                        ans[1] += int(p[:-1]) * flag\n",
    "                else:\n",
    "                    ans[0] += flag * int(p)\n",
    "        equation = equation.replace('-', '+-')\n",
    "        ans = [0, 0]\n",
    "        left, right = equation.split('=')\n",
    "        get_part(ans, left, 1)\n",
    "        get_part(ans, right, -1)\n",
    "        \n",
    "        if ans[1] == 0:\n",
    "            if ans[0] == 0:\n",
    "                return \"Infinite solutions\"\n",
    "            else:\n",
    "                return \"No solution\"\n",
    "        return f\"x={-ans[0] // ans[1]}\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from typing import List\n",
    "from collections import defaultdict\n",
    "from functools import cache\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    logs = \"\"\n",
    "\n",
    "    def log(self, s):\n",
    "        self.logs += f'{s}\\n'\n",
    "\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        left_right = [0, 0]\n",
    "        has_eq = 1\n",
    "        tmp_value = 0\n",
    "        is_x = False\n",
    "        last_op = 1\n",
    "        equation = equation.replace('0x', '0')\n",
    "\n",
    "        def hander(value, index):\n",
    "            left_right[index] += value\n",
    "            self.log([value, is_x])\n",
    "        for v in equation:\n",
    "            is_x = 0\n",
    "            if ord('0') <= ord(v) <= ord('9'):\n",
    "                tmp_value = tmp_value*10+int(v)\n",
    "            else:\n",
    "                if v == '=':\n",
    "                    if tmp_value:\n",
    "                        hander(last_op*tmp_value*has_eq, is_x)\n",
    "                        tmp_value = 0\n",
    "                    has_eq = -1\n",
    "                    last_op = 1\n",
    "                    continue\n",
    "                if v == 'x':\n",
    "                    if not tmp_value:\n",
    "                        tmp_value = 1\n",
    "                    is_x = 1\n",
    "                if tmp_value:\n",
    "                    hander(last_op*tmp_value*has_eq, is_x)\n",
    "                    tmp_value = 0\n",
    "                if v == '+':\n",
    "                    last_op = 1\n",
    "                if v == '-':\n",
    "                    last_op = -1\n",
    "\n",
    "        if tmp_value:\n",
    "            hander(last_op*tmp_value*has_eq, is_x)\n",
    "        if left_right[1] == 0:\n",
    "            if left_right[0] == 0:\n",
    "                return 'Infinite solutions'\n",
    "            return \"No solution\"\n",
    "        return f'x={left_right[0]//-left_right[1]}'\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    s = Solution()\n",
    "    for case in [\n",
    "        [\"x+5-3+x=6+x-2\", \"x=2\"],\n",
    "        [\"2x+3x-6x=x+2\", \"x=-1\"],\n",
    "        [\"x=x+2\", \"No solution\"],\n",
    "        [\"x=x\", \"Infinite solutions\"],\n",
    "        [\"2x=x\", \"x=0\"],\n",
    "        [\"2=-x\", \"x=-2\"],\n",
    "        [\"0x=0\", \"Infinite solutions\"],\n",
    "        [\"1+1=x\", \"x=2\"]\n",
    "    ]:\n",
    "        s.logs = \"\"\n",
    "        e = s.solveEquation(*case[:-1])\n",
    "        if e != case[-1]:\n",
    "            print(e, case)\n",
    "            print(s.logs)\n",
    "            break\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        #左,右子项分割等式项\n",
    "        left, right = equation.split('=')\n",
    "        #定义一个fn函数\n",
    "        def fn(s): \n",
    "            ii = x = y = 0\n",
    "            for i in range(len(s)+1):\n",
    "                #计算常量值\n",
    "                if i == len(s) or s[i] in \"+-\": \n",
    "                    if ii < i: \n",
    "                        y += int(s[ii:i])\n",
    "                        \n",
    "                    ii = i\n",
    "                #计算带有x的值\n",
    "                elif s[i] == \"x\":\n",
    "                    if ii == i or s[ii:i] in \"+-\": \n",
    "                        x += int(s[ii:i] + \"1\")\n",
    "                    else: \n",
    "                        x += int(s[ii:i])\n",
    "                    ii = i+1\n",
    "            return x, y\n",
    "        \n",
    "        (lx, ly), (rx, ry) = fn(left), fn(right)\n",
    "        print(lx,ly)\n",
    "        print(rx,ry)\n",
    "        if lx == rx:\n",
    "            if ly == ry: \n",
    "                return 'Infinite solutions'\n",
    "            else: \n",
    "                return 'No solution'\n",
    "        \n",
    "        return f'x={(ry - ly) // (lx - rx)}'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        n = len(equation)\n",
    "        x = c = i = 0\n",
    "        while i < n:\n",
    "            if equation[i] == \"=\":\n",
    "                x *= -1\n",
    "                c *= -1\n",
    "                i += 1\n",
    "                continue\n",
    "\n",
    "            signal = 1\n",
    "            if equation[i] == \"+\":\n",
    "                i += 1\n",
    "            elif equation[i] == \"-\":\n",
    "                signal = -1\n",
    "                i += 1\n",
    "\n",
    "            num = 0\n",
    "            digit = False\n",
    "            while i < n and equation[i].isdigit():\n",
    "                digit = True\n",
    "                num = num * 10 + int(equation[i])\n",
    "                i += 1\n",
    "                \n",
    "            if i<n and equation[i] == \"x\":\n",
    "                x += signal * (num if digit else 1)\n",
    "                i += 1\n",
    "            else:\n",
    "                c += signal * num\n",
    "\n",
    "        if x == 0:\n",
    "            return \"No solution\" if c else \"Infinite solutions\"\n",
    "\n",
    "        return f\"x={-c//x}\"\n",
    "\n",
    "            \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        n = len(equation)\n",
    "        i = 0\n",
    "        xishux = xishuc = 0\n",
    "        sign = 1\n",
    "        while i < n:\n",
    "            if equation[i] == '=':\n",
    "                sign = -1\n",
    "                i += 1\n",
    "                continue\n",
    "\n",
    "            s = sign\n",
    "            if equation[i] == '-':\n",
    "                s = -s\n",
    "                i += 1\n",
    "            elif equation[i] == '+':\n",
    "                i += 1\n",
    "\n",
    "            num = 0\n",
    "            valid = False\n",
    "            while i < n and equation[i].isdigit():\n",
    "                valid = True\n",
    "                num = num * 10 + int(equation[i])\n",
    "                i += 1\n",
    "\n",
    "            if i < n and equation[i] == 'x':\n",
    "                xishux += num * s if valid else 1 * s\n",
    "                i += 1\n",
    "            else:\n",
    "                xishuc += num * s\n",
    "            print(xishuc, xishux)\n",
    "        if xishux == 0:\n",
    "            if xishuc == 0: return 'Infinite solutions'\n",
    "            else: return 'No solution'\n",
    "        \n",
    "        return 'x='+str(-xishuc//xishux)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        k = [0, 0]\n",
    "        b = [0, 0] \n",
    "        sign = [1, 1]\n",
    "        idx = 0  \n",
    "        n = len(equation)\n",
    "        i = 0\n",
    "        while i < n:\n",
    "            if equation[i] == '+':\n",
    "                i+=1\n",
    "            elif equation[i] == '-':\n",
    "                sign[idx] = -1 * sign[idx]\n",
    "                i+=1\n",
    "            elif equation[i] == '=':\n",
    "                idx += 1\n",
    "                i+=1\n",
    "            elif equation[i].isdigit():\n",
    "                num = 0 \n",
    "                while i < n and equation[i].isdigit():\n",
    "                    num = num * 10 + int(equation[i])\n",
    "                    i+=1\n",
    "                if i < n and equation[i].isalpha():\n",
    "                    k[idx] += sign[idx] * num \n",
    "                    sign[idx]=1\n",
    "                    i+=1\n",
    "                else:\n",
    "                    b[idx] += sign[idx] * num \n",
    "                    sign[idx]=1\n",
    "            elif equation[i].isalpha():\n",
    "                k[idx] += sign[idx]\n",
    "                sign[idx] = 1\n",
    "                i+=1 \n",
    "        k[0] -= k[1]\n",
    "        k[1] = 0\n",
    "        b[1] -= b[0]\n",
    "        b[0] = 0 \n",
    "        if b[1] == 0 and k[0] == 0:\n",
    "            return 'Infinite solutions'\n",
    "        elif k[0] == 0 and b[1] != 0:\n",
    "            return 'No solution'\n",
    "        else:\n",
    "            return 'x={}'.format(b[1]//k[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        def change(s):\n",
    "            i = 0\n",
    "            number = []\n",
    "            fac_coef = []\n",
    "            n = len(s)\n",
    "            while i < n:\n",
    "                flag = 1\n",
    "                if i < n and s[i] == '+':\n",
    "                    i = i+1\n",
    "                if i < n and s[i] == '-':\n",
    "                    flag = -flag\n",
    "                    i = i+1\n",
    "                isnum = False\n",
    "                num = 0\n",
    "                while i < n and s[i].isdigit():        \n",
    "                    isnum = True\n",
    "                    num = num*10 + int(s[i])\n",
    "                    i = i+1\n",
    "                    \n",
    "                if i < n and s[i] == 'x':\n",
    "                    if isnum:\n",
    "                        fac_coef.append(flag*num)\n",
    "                        i = i+1\n",
    "                    else: \n",
    "                        fac_coef.append(flag)\n",
    "                        i = i+1\n",
    "                else:\n",
    "                    if isnum:\n",
    "                        number.append(flag*num)\n",
    "            return sum(number), sum(fac_coef)\n",
    "        equation1 = equation.split('=')\n",
    "        num_left, coef_left = change(equation1[0])\n",
    "        num_right, coef_right = change(equation1[1])\n",
    "        allnum = num_left - num_right\n",
    "        allcoef = coef_left - coef_right\n",
    "\n",
    "        if allcoef==0:\n",
    "            return \"Infinite solutions\" if allnum == 0 else \"No solution\"\n",
    "        return f\"x={(-1)*allnum//allcoef}\" if not (allnum % allcoef) else \"No solution\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        # 1. 等式分为两边 等号左边计入left 右边计入right\n",
    "        # 2. 建立left_num, left_x, right_num, right_x \n",
    "        index = equation.index('=')\n",
    "        num, flag = 0, 1\n",
    "        left_stack, right_stack = [], []\n",
    "        left_x, right_x = 0, 0\n",
    "        x_zero = -1 #标记x前面是否为0\n",
    "        for i in range(index):\n",
    "            if equation[i] == 'x':\n",
    "                if x_zero == 0:\n",
    "                    pass\n",
    "                else:\n",
    "                    left_x += num * flag if num else flag\n",
    "                num = 0\n",
    "            elif equation[i] == '+':\n",
    "                left_stack.append(flag * num)\n",
    "                num, flag = 0, 1\n",
    "            elif equation[i] == '-':\n",
    "                left_stack.append(flag * num)\n",
    "                num, flag = 0 , -1\n",
    "            else:\n",
    "                #数字\n",
    "                num =10 * num + int(equation[i])\n",
    "                x_zero = num   \n",
    "        if num:\n",
    "            left_stack.append(num * flag)\n",
    "        num, flag = 0, 1\n",
    "        x_zero = -1\n",
    "        for j in range(index + 1, len(equation)):\n",
    "            if equation[j] == 'x':\n",
    "                if x_zero == 0:\n",
    "                    pass\n",
    "                else:\n",
    "                    right_x += num * flag if num else flag\n",
    "                num = 0\n",
    "            elif equation[j] == '+':\n",
    "                right_stack.append(flag * num)\n",
    "                num, flag = 0, 1\n",
    "            elif equation[j] == '-':\n",
    "                right_stack.append(flag * num)\n",
    "                num, flag = 0 , -1\n",
    "            else:\n",
    "                #数字\n",
    "                num =10 * num + int(equation[j])\n",
    "                x_zero = num\n",
    "        if num:\n",
    "            right_stack.append(num * flag)\n",
    "\n",
    "        sum_left = sum(left_stack)\n",
    "        sum_right = sum(right_stack)\n",
    "        # print(left_x, right_x)\n",
    "        print(left_stack, right_stack)\n",
    "        if left_x == right_x and sum_left == sum_right:\n",
    "            return \"Infinite solutions\"\n",
    "        elif left_x == right_x and sum_left != sum_right:\n",
    "            return \"No solution\"\n",
    "        else:\n",
    "            return f'x={str((sum_right - sum_left) // (left_x - right_x))}'\n",
    "        # elif left_x > right_x:\n",
    "        #     return \"x=\" + str((sum_right - sum_left) // (left_x - right_x))\n",
    "        # else:\n",
    "        #     return \"x=\" + str((sum_left - sum_right) // (right_x - left_x))\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        def evaluate(expression):\n",
    "            sum_x, sum_val = 0, 0\n",
    "            sign, num = 1, \"\"\n",
    "\n",
    "            for ch in expression + '+':\n",
    "                if ch in ['+', '-']:\n",
    "                    if num:\n",
    "                        if 'x' in num:\n",
    "                            coef = num.replace('x', '') or '1'\n",
    "                            sum_x += sign * int(coef)\n",
    "                        else:\n",
    "                            sum_val += sign * int(num)\n",
    "                    num = \"\"\n",
    "                    sign = 1 if ch == '+' else -1\n",
    "                else:\n",
    "                    num += ch\n",
    "            return sum_x, sum_val\n",
    "        \n",
    "        left, right = equation.split('=')\n",
    "        left_x, left_val = evaluate(left)\n",
    "        right_x, right_val = evaluate(right)\n",
    "\n",
    "        coef = left_x - right_x\n",
    "        const = right_val - left_val\n",
    "\n",
    "        if coef == 0:\n",
    "            if const == 0:\n",
    "                return \"Infinite solutions\"\n",
    "            else:\n",
    "                return \"No solution\"\n",
    "        else:\n",
    "            return \"x=\" + str(const // coef)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        # 1. 等式分为两边 等号左边计入left 右边计入right\n",
    "        # 2. 建立left_num, left_x, right_num, right_x \n",
    "        index = equation.index('=')\n",
    "        num, flag = 0, 1\n",
    "        left_stack, right_stack = [], []\n",
    "        left_x, right_x = 0, 0\n",
    "        x_zero = -1\n",
    "        for i in range(index):\n",
    "            if equation[i] == 'x':\n",
    "                if x_zero == 0:\n",
    "                    left_x = 0\n",
    "                else:\n",
    "                    left_x += num * flag if num else flag\n",
    "                num = 0\n",
    "            elif equation[i] == '+':\n",
    "                left_stack.append(flag * num)\n",
    "                num, flag = 0, 1\n",
    "            elif equation[i] == '-':\n",
    "                left_stack.append(flag * num)\n",
    "                num, flag = 0 , -1\n",
    "            else:\n",
    "                #数字\n",
    "                num =10 * num + int(equation[i])\n",
    "                x_zero = num   \n",
    "        if num:\n",
    "            left_stack.append(num * flag)\n",
    "        num, flag = 0, 1\n",
    "        x_zero = -1\n",
    "        for j in range(index + 1, len(equation)):\n",
    "            if equation[j] == 'x':\n",
    "                if x_zero == 0:\n",
    "                    right_x = 0\n",
    "                else:\n",
    "                    right_x += num * flag if num else flag\n",
    "                num = 0\n",
    "            elif equation[j] == '+':\n",
    "                right_stack.append(flag * num)\n",
    "                num, flag = 0, 1\n",
    "            elif equation[j] == '-':\n",
    "                right_stack.append(flag * num)\n",
    "                num, flag = 0 , -1\n",
    "            else:\n",
    "                #数字\n",
    "                num =10 * num + int(equation[j])\n",
    "                x_zero = num\n",
    "        if num:\n",
    "            right_stack.append(num * flag)\n",
    "        sum_left = sum(left_stack)\n",
    "        sum_right = sum(right_stack)\n",
    "        # print(left_x, right_x)\n",
    "        print(left_stack, right_stack)\n",
    "        if left_x == right_x and sum_left == sum_right:\n",
    "            return \"Infinite solutions\"\n",
    "        elif left_x == right_x and sum_left != sum_right:\n",
    "            return \"No solution\"\n",
    "        elif left_x > right_x:\n",
    "            return \"x=\" + str((sum_right - sum_left) // (left_x - right_x))\n",
    "        else:\n",
    "            return \"x=\" + str((sum_left - sum_right) // (right_x - left_x))\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        equation = equation.split(\"=\")\n",
    "        left, right = equation[0]+\"+\", equation[1]+\"+\"\n",
    "        l_x = []\n",
    "        l_n = []\n",
    "        r_x = []\n",
    "        r_n = []\n",
    "        p, q = 0, 1\n",
    "        while q<len(left):\n",
    "            if left[q]=='+' or left[q]=='-':\n",
    "                s = left[p:q]\n",
    "                if s[-1]=='x':\n",
    "                    l_x.append(s[:-1])\n",
    "                else:\n",
    "                    l_n.append(s)\n",
    "                p = q\n",
    "            q += 1\n",
    "        p, q = 0, 1\n",
    "        while q<len(right):\n",
    "            if right[q]=='+' or right[q]=='-':\n",
    "                s = right[p:q]\n",
    "                if s[-1]=='x':\n",
    "                    r_x.append(s[:-1])\n",
    "                else:\n",
    "                    r_n.append(s)\n",
    "                p = q\n",
    "            q += 1\n",
    "        sum_n = 0\n",
    "        sum_x = 0\n",
    "        for s in l_n:\n",
    "            sum_n -= int(s)\n",
    "        for s in r_n:\n",
    "            sum_n += int(s)\n",
    "        for s in l_x:\n",
    "            if s=='' or s=='+':\n",
    "                sum_x += 1\n",
    "            elif s=='-':\n",
    "                sum_x += -1\n",
    "            else:\n",
    "                sum_x += int(s)\n",
    "        for s in r_x:\n",
    "            if s=='' or s=='+':\n",
    "                sum_x -= 1\n",
    "            elif s=='-':\n",
    "                sum_x -= -1\n",
    "            else:\n",
    "                sum_x -= int(s)\n",
    "        # print(l_x, sum_n)\n",
    "        if sum_x==0 and sum_n==0:\n",
    "            return \"Infinite solutions\"\n",
    "        if sum_x==0 and sum_n!=0:\n",
    "            return \"No solution\"\n",
    "        else:\n",
    "            return \"x=\"+str(int(sum_n/sum_x))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        # factor表示变量系数和，val表示数字和, 本质只需要维护factor和val\n",
    "        factor, val = 0, 0\n",
    "        n = len(equation)\n",
    "        lr_sign, pn_sign = 1, 1 #等式左边默认系数为正\n",
    "        num = 'initial'\n",
    "        for i in range(n):\n",
    "            # 开始模拟\n",
    "            if equation[i] == '=':\n",
    "                if num != 'initial':\n",
    "                    val += num * pn_sign\n",
    "                lr_sign = -1\n",
    "                pn_sign = lr_sign\n",
    "                num = 'initial'\n",
    "            elif equation[i] == 'x':\n",
    "                if num != 'initial':\n",
    "                    factor += pn_sign * num\n",
    "                else:\n",
    "                    factor += pn_sign\n",
    "                num = 'initial'\n",
    "            elif equation[i] == '+':\n",
    "                if num != 'initial':\n",
    "                    val += num * pn_sign\n",
    "                pn_sign = lr_sign\n",
    "                num = 'initial'\n",
    "            elif equation[i] == '-':\n",
    "                if num != 'initial':\n",
    "                    val += num * pn_sign\n",
    "                pn_sign = - lr_sign\n",
    "                num = 'initial'\n",
    "            elif equation[i].isdigit(): # 数\n",
    "                if num != 'initial':\n",
    "                    num = 10 * num + int(equation[i])\n",
    "                else:\n",
    "                    num = int(equation[i])\n",
    "\n",
    "            if i == n-1:\n",
    "                if num != 'initial':\n",
    "                    val += num * pn_sign\n",
    "\n",
    "        if factor == 0:\n",
    "            if val == 0:\n",
    "                ans = \"Infinite solutions\"\n",
    "            else:\n",
    "                ans = \"No solution\"\n",
    "        else:\n",
    "            ans = f\"x={int(-val / factor)}\" if -val/factor == int(-val/factor) else \"No solution\"\n",
    "        return ans\n",
    "\n",
    "\n",
    "            \n",
    "        \n",
    "        \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "\"\"\"\n",
    "    模拟\n",
    "\"\"\"\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        n = len(equation)\n",
    "        lis = []\n",
    "        prev = 0\n",
    "        for i, ch in enumerate(equation):\n",
    "            if ch != \"+\" and ch != \"-\" and ch != \"=\":\n",
    "                prev += 1\n",
    "            else:\n",
    "                lis.append(equation[i-prev:i])\n",
    "                lis.append(equation[i])\n",
    "                prev = 0\n",
    "        lis.append(equation[n-prev:n])\n",
    "        alpha, beta = 0, 0 \n",
    "        tag = 1   # 是否出现= 1, -1\n",
    "        prev = 1\n",
    "        for s in lis:\n",
    "            if len(s) == 0:\n",
    "                continue\n",
    "            if s[-1] == \"x\":\n",
    "                if len(s) == 1:\n",
    "                    alpha += prev * tag\n",
    "                else:\n",
    "                    alpha += int(s[:-1]) * prev * tag\n",
    "                prev = 1\n",
    "            elif s == \"-\":\n",
    "                prev = -1\n",
    "            elif s == \"=\":\n",
    "                tag = -1\n",
    "            elif s.isdigit():\n",
    "                beta -= int(s) * prev * tag\n",
    "                prev = 1\n",
    "        \n",
    "        if alpha == 0 and beta == 0:\n",
    "            return \"Infinite solutions\"\n",
    "        elif alpha == 0:\n",
    "            return \"No solution\"\n",
    "        return f\"x={beta//alpha}\"\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        a, b, sign = 0, 0, 1\n",
    "        length = len(equation)\n",
    "        index = 0\n",
    "\n",
    "        while index < length:\n",
    "\n",
    "            if equation[index] == \"=\":\n",
    "                sign = sign*(-1)\n",
    "                index += 1\n",
    "                continue\n",
    "\n",
    "            sign_tmp = sign\n",
    "\n",
    "            if equation[index] == \"+\":\n",
    "                index += 1\n",
    "            elif equation[index] == \"-\":\n",
    "                sign_tmp = sign_tmp*(-1)\n",
    "                index += 1\n",
    "            \n",
    "            digit_num, flag = 0, False\n",
    "            while index < length and (\"0\" <= equation[index] <= \"9\"):\n",
    "                digit_num = 10*digit_num + int(equation[index])\n",
    "                index += 1\n",
    "                flag = True\n",
    "\n",
    "            if index < length and equation[index] == \"x\":\n",
    "                if flag:\n",
    "                    a = a + sign_tmp*digit_num\n",
    "                else:\n",
    "                    a = a + sign_tmp\n",
    "                index += 1\n",
    "            else:\n",
    "                b = b + sign_tmp*digit_num\n",
    "\n",
    "        if a == 0:\n",
    "            return \"No solution\" if b else \"Infinite solutions\"\n",
    "\n",
    "        return f\"x={-b//a}\"\n",
    "\n",
    "            \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "         # 1. 等式分为两边 等号左边计入left 右边计入right\n",
    "        # 2. 建立left_num, left_x, right_num, right_x \n",
    "        index = equation.index('=')\n",
    "        def get_res(start, end, flag):\n",
    "            val_sum, val_x, num = 0, 0, 0\n",
    "            x_zero = -1\n",
    "            for i in range(start, end):\n",
    "                if equation[i] == 'x':\n",
    "                    #x系数不为0\n",
    "                    if x_zero != 0:\n",
    "                        val_x += num * flag if num else flag\n",
    "                    num = 0\n",
    "                elif equation[i] == '+':\n",
    "                    val_sum += flag * num\n",
    "                    num, flag = 0, 1\n",
    "                elif equation[i] == '-':\n",
    "                    val_sum += flag * num\n",
    "                    num, flag = 0 , -1\n",
    "                else:\n",
    "                    num =10 * num + int(equation[i])\n",
    "                    x_zero = num # 考虑x系数是否为0\n",
    "            val_sum += flag * num\n",
    "            return val_sum, val_x\n",
    "        sum_left, left_x = get_res(0, index, 1)\n",
    "        sum_right, right_x = get_res(index + 1, len(equation), 1)\n",
    "\n",
    "        if left_x == right_x and sum_left == sum_right:\n",
    "            return \"Infinite solutions\"\n",
    "        elif left_x == right_x and sum_left != sum_right:\n",
    "            return \"No solution\"\n",
    "        else:\n",
    "            return f'x={str((sum_right - sum_left) // (left_x - right_x))}'\n",
    "    \n",
    "                \n",
    "\n",
    "        \n",
    "        \n",
    "    \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, q: str) -> str:\n",
    "        right = 1\n",
    "        fuhao = 1\n",
    "        tmp = \"\"\n",
    "        A = B = 0\n",
    "        for s in q:\n",
    "            if s in \"+-=\":\n",
    "                B += fuhao * (int(tmp) if tmp else 0) * right\n",
    "                tmp = \"\"\n",
    "                if s == \"=\":\n",
    "                    right = -1\n",
    "                    fuhao = 1\n",
    "                elif s == \"+\":\n",
    "                    fuhao = 1\n",
    "                elif s == \"-\":\n",
    "                    fuhao = -1\n",
    "            elif s == \"x\":\n",
    "                A += fuhao * (int(tmp) if tmp else 1) * right\n",
    "                tmp = \"\"\n",
    "            else:\n",
    "                tmp += s\n",
    "        if tmp:\n",
    "            B += fuhao * (int(tmp) if tmp else 1) * right\n",
    "        if A == 0:\n",
    "            return \"Infinite solutions\" if B == 0 else \"No solution\"\n",
    "        return \"x=\" + str( -1 * B // A)\n",
    "\n",
    "                \n",
    "\n",
    "\n",
    "\n",
    "\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        factor = val = 0\n",
    "        i, n, sign = 0, len(equation), 1  # 等式左边默认系数为正\n",
    "        while i < n:\n",
    "            if equation[i] == '=':\n",
    "                sign = -1\n",
    "                i += 1\n",
    "                continue\n",
    "\n",
    "            s = sign\n",
    "            if equation[i] == '+':  # 去掉前面的符号\n",
    "                i += 1\n",
    "            elif equation[i] == '-':\n",
    "                s = -s\n",
    "                i += 1\n",
    "\n",
    "            num, valid = 0, False\n",
    "            while i < n and equation[i].isdigit():\n",
    "                valid = True\n",
    "                num = num * 10 + int(equation[i])\n",
    "                i += 1\n",
    "\n",
    "            if i < n and equation[i] == 'x':  # 变量\n",
    "                factor += s * num if valid else s\n",
    "                i += 1\n",
    "            else:  # 数值\n",
    "                val += s * num\n",
    "\n",
    "        if factor == 0:\n",
    "            return \"No solution\" if val else \"Infinite solutions\"\n",
    "        return f\"x={-val // factor}\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        # 1. 等式分为两边 等号左边计入left 右边计入right\n",
    "        # 2. 建立left_num, left_x, right_num, right_x \n",
    "        index = equation.index('=')\n",
    "        num, flag = 0, 1\n",
    "        left_stack, right_stack = [], []\n",
    "        left_x, right_x = 0, 0\n",
    "        x_zero = -1\n",
    "        for i in range(index):\n",
    "            if equation[i] == 'x':\n",
    "                if x_zero == 0:\n",
    "                    left_x += 0\n",
    "                else:\n",
    "                    left_x += num * flag if num else flag\n",
    "                num = 0\n",
    "            elif equation[i] == '+':\n",
    "                left_stack.append(flag * num)\n",
    "                num, flag = 0, 1\n",
    "            elif equation[i] == '-':\n",
    "                left_stack.append(flag * num)\n",
    "                num, flag = 0 , -1\n",
    "            else:\n",
    "                #数字\n",
    "                num =10 * num + int(equation[i])\n",
    "                x_zero = num   \n",
    "        if num:\n",
    "            left_stack.append(num * flag)\n",
    "        num, flag = 0, 1\n",
    "        x_zero = -1\n",
    "        for j in range(index + 1, len(equation)):\n",
    "            if equation[j] == 'x':\n",
    "                if x_zero == 0:\n",
    "                    right_x += 0\n",
    "                else:\n",
    "                    right_x += num * flag if num else flag\n",
    "                num = 0\n",
    "            elif equation[j] == '+':\n",
    "                right_stack.append(flag * num)\n",
    "                num, flag = 0, 1\n",
    "            elif equation[j] == '-':\n",
    "                right_stack.append(flag * num)\n",
    "                num, flag = 0 , -1\n",
    "            else:\n",
    "                #数字\n",
    "                num =10 * num + int(equation[j])\n",
    "                x_zero = num\n",
    "        if num:\n",
    "            right_stack.append(num * flag)\n",
    "        sum_left = sum(left_stack)\n",
    "        sum_right = sum(right_stack)\n",
    "        # print(left_x, right_x)\n",
    "        print(left_stack, right_stack)\n",
    "        if left_x == right_x and sum_left == sum_right:\n",
    "            return \"Infinite solutions\"\n",
    "        elif left_x == right_x and sum_left != sum_right:\n",
    "            return \"No solution\"\n",
    "        elif left_x > right_x:\n",
    "            return \"x=\" + str((sum_right - sum_left) // (left_x - right_x))\n",
    "        else:\n",
    "            return \"x=\" + str((sum_left - sum_right) // (right_x - left_x))\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        factor = val = 0\n",
    "        i, n, sign = 0, len(equation), 1  # 等式左边默认系数为正\n",
    "        while i < n:\n",
    "            if equation[i] == '=':\n",
    "                sign = -1\n",
    "                i += 1\n",
    "                continue\n",
    "\n",
    "            s = sign\n",
    "            if equation[i] == '+':  # 去掉前面的符号\n",
    "                i += 1\n",
    "            elif equation[i] == '-':\n",
    "                s = -s\n",
    "                i += 1\n",
    "\n",
    "            num, valid = 0, False\n",
    "            while i < n and equation[i].isdigit():\n",
    "                valid = True\n",
    "                num = num * 10 + int(equation[i])\n",
    "                i += 1\n",
    "\n",
    "            if i < n and equation[i] == 'x':  # 变量\n",
    "                factor += s * num if valid else s\n",
    "                i += 1\n",
    "            else:  # 数值\n",
    "                val += s * num\n",
    "\n",
    "        if factor == 0:\n",
    "            return \"No solution\" if val else \"Infinite solutions\"\n",
    "        return f\"x={-val // factor}\"\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "         # 1. 等式分为两边 等号左边计入left 右边计入right\n",
    "        # 2. 建立left_num, left_x, right_num, right_x \n",
    "        index = equation.index('=')\n",
    "        def get_res(start, end, flag):\n",
    "            val_sum, val_x, num = 0, 0, 0\n",
    "            x_zero = -1\n",
    "            for i in range(start, end):\n",
    "                if equation[i] == 'x':\n",
    "                    #x系数不为0\n",
    "                    if x_zero != 0:\n",
    "                        val_x += num * flag if num else flag\n",
    "                    num = 0\n",
    "                elif equation[i] == '+':\n",
    "                    val_sum += flag * num\n",
    "                    num, flag = 0, 1\n",
    "                elif equation[i] == '-':\n",
    "                    val_sum += flag * num\n",
    "                    num, flag = 0 , -1\n",
    "                else:\n",
    "                    num =10 * num + int(equation[i])\n",
    "                    x_zero = num # 考虑x系数是否为0\n",
    "            val_sum += flag * num\n",
    "            return val_sum, val_x\n",
    "        sum_left, left_x = get_res(0, index, 1)\n",
    "        sum_right, right_x = get_res(index + 1, len(equation), 1)\n",
    "\n",
    "        if left_x == right_x and sum_left == sum_right:\n",
    "            return \"Infinite solutions\"\n",
    "        elif left_x == right_x and sum_left != sum_right:\n",
    "            return \"No solution\"\n",
    "        else:\n",
    "            return f'x={str((sum_right - sum_left) // (left_x - right_x))}'\n",
    "    \n",
    "                \n",
    "\n",
    "        \n",
    "        \n",
    "    \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        new_equation=equation.replace('-','+-')\n",
    "        equation=new_equation.split('=')\n",
    "        LHS=equation[0].split('+')\n",
    "        RHS=equation[1].split('+')\n",
    "        left_coeff=0\n",
    "        left_num=0\n",
    "        right_coeff=0\n",
    "        right_num=0\n",
    "        for i in range(len(LHS)):\n",
    "            if len(LHS[i])==0:\n",
    "                continue\n",
    "            if LHS[i][-1]=='x':\n",
    "                if len(LHS[i])==1:\n",
    "                    left_coeff+=1\n",
    "                elif len(LHS[i])==2:\n",
    "                    if LHS[i][0]=='-':\n",
    "                        left_coeff-=1\n",
    "                    else:\n",
    "                        left_coeff+=int(LHS[i][0])\n",
    "                else:\n",
    "                    left_coeff+=int(LHS[i][:-1])\n",
    "            else:\n",
    "                left_num+=int(LHS[i])\n",
    "        for i in range(len(RHS)):\n",
    "            if len(RHS[i])==0:\n",
    "                continue\n",
    "            if RHS[i][-1]=='x':\n",
    "                if len(RHS[i])==1:\n",
    "                    right_coeff+=1\n",
    "                elif len(RHS[i])==2:\n",
    "                    if RHS[i][0]=='-':\n",
    "                        right_coeff-=1\n",
    "                    else:\n",
    "                        right_coeff+=int(RHS[i][0])\n",
    "                else:\n",
    "                    right_coeff+=int(RHS[i][:-1])\n",
    "            else:\n",
    "                right_num+=int(RHS[i])\n",
    "        if (right_coeff-left_coeff)==0 and right_num-left_num!=0:\n",
    "            return 'No solution'\n",
    "        elif (right_coeff-left_coeff)==0 and right_num-left_num==0:\n",
    "            return 'Infinite solutions'\n",
    "        else:\n",
    "            return 'x='+str(-(right_num-left_num)//(right_coeff-left_coeff))\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        equations = equation.split(\"=\")\n",
    "        left, right = equations[0], equations[1]\n",
    "\n",
    "        def parse(strs):\n",
    "            nums = 0\n",
    "            x_cnt = 0\n",
    "            pre, symbol = \"\", 1\n",
    "            for i in strs:\n",
    "                if i.isdigit():\n",
    "                    pre += i \n",
    "                elif i in [\"+\", \"-\"]:\n",
    "                    nums += int(pre)*symbol if pre != \"\" else 0\n",
    "                    if i == \"-\":\n",
    "                        symbol = -1\n",
    "                    else:\n",
    "                        symbol = 1\n",
    "                    pre = \"\"\n",
    "                elif i == \"x\":\n",
    "                    x_cnt += (int(pre) if pre != \"\" else 1) * symbol\n",
    "                    pre = \"\"\n",
    "            if pre != \"\":\n",
    "                nums += int(pre)*symbol\n",
    "            return nums, x_cnt\n",
    "        ln, lx = parse(left)\n",
    "        rn, rx = parse(right)\n",
    "        if lx-rx == 0:\n",
    "            if rn-ln == 0:\n",
    "                return \"Infinite solutions\"\n",
    "            return \"No solution\"\n",
    "        res = (rn-ln)//(lx-rx)\n",
    "        return \"x=\" + str(res)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        sign = 1\n",
    "        left = 1\n",
    "        i = 0\n",
    "        x_num = 0\n",
    "        const = 0\n",
    "        n = len(equation)\n",
    "        num = 1\n",
    "        while i < n:\n",
    "            if equation[i] == 'x':\n",
    "                x_num += left*sign*num\n",
    "                num = 1\n",
    "                sign=1\n",
    "            elif equation[i] == '=':\n",
    "                if left==-1:\n",
    "                    return 'No solution'\n",
    "                left = -1\n",
    "            elif equation[i] == '+':\n",
    "                sign = 1\n",
    "            elif equation[i] == '-':\n",
    "                sign = -1\n",
    "            else:\n",
    "                num = 0\n",
    "                while i < n and equation[i].isdigit():\n",
    "                    num = num*10+int(equation[i])\n",
    "                    i += 1\n",
    "                if i == n or equation[i] != 'x':\n",
    "                    const -= sign*left*num\n",
    "                    num = 1\n",
    "                    sign=1\n",
    "                i -= 1\n",
    "            i += 1\n",
    "        if x_num == 0 and const==0:\n",
    "            return 'Infinite solutions'\n",
    "        elif x_num==0 and const!=0 or const % x_num != 0:\n",
    "            return 'No solution'\n",
    "        else:\n",
    "            return f'x={const//x_num}'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        equation = equation.replace('-', '+-')\n",
    "        equation = equation.strip().split('=')\n",
    "        left = equation[0].split('+')\n",
    "        right = equation[1].split('+')\n",
    "        pre = C = 0\n",
    "        for i in left:\n",
    "            if not i: continue\n",
    "            if 'x' in i:\n",
    "                if len(i) == 1: pre += 1\n",
    "                elif len(i) == 2 and  '-' in i: pre -= 1\n",
    "                else: pre += int(i[:-1])\n",
    "            else:\n",
    "                C -= int(i)\n",
    "        for i in right:\n",
    "            if not i: continue\n",
    "            if 'x' in i:\n",
    "                if len(i) == 1: pre -= 1\n",
    "                elif len(i) == 2 and  '-' in i: pre += 1\n",
    "                else: pre -= int(i[:-1])\n",
    "            else:\n",
    "                C += int(i)\n",
    "        if pre == 0 and C == 0:\n",
    "            return 'Infinite solutions'\n",
    "        if pre == 0:\n",
    "            return 'No solution'\n",
    "        return 'x='+str(C//pre)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        leftStr = equation.split(\"=\")[0]\n",
    "        rightStr = equation.split(\"=\")[1]\n",
    "        leftACount = 0\n",
    "        leftNumCount = 0\n",
    "        rightACount = 0\n",
    "        rightNumCount = 0\n",
    "\n",
    "        def getCount(s:str):\n",
    "            acount = 0\n",
    "            numcount = 0\n",
    "            tmp = []\n",
    "            fuhao = 1\n",
    "            isA = False\n",
    "            for i in s:\n",
    "                if i==\"x\":\n",
    "                    if len(tmp)==0:\n",
    "                        acount+=fuhao\n",
    "                    else:\n",
    "                        acount+=int(\"\".join(tmp)) * fuhao\n",
    "                    tmp = []\n",
    "                    isA=True\n",
    "                elif i==\"+\":\n",
    "                    if isA:\n",
    "                        fuhao=1\n",
    "                        continue\n",
    "                    if tmp:\n",
    "                        numcount+=fuhao*int(\"\".join(tmp))\n",
    "                    tmp=[]\n",
    "                    fuhao=1\n",
    "                    isA=False\n",
    "                elif i ==\"-\":\n",
    "                    if isA:\n",
    "                        fuhao=-1\n",
    "                        continue\n",
    "                    if tmp:\n",
    "                        numcount+=fuhao*int(\"\".join(tmp))\n",
    "                    tmp=[]\n",
    "                    fuhao=-1\n",
    "                    isA=False\n",
    "                else:\n",
    "                    #数字\n",
    "                    tmp.append(i)\n",
    "                    isA=False\n",
    "            if tmp:\n",
    "                numcount+=fuhao*int(\"\".join(tmp))\n",
    "            return acount,numcount\n",
    "        leftACount,leftNumCount= getCount(leftStr)\n",
    "        rightACount,rightNumCount= getCount(rightStr)\n",
    "        if (leftACount-rightACount)==0:\n",
    "            if (rightNumCount-leftNumCount)!=0:\n",
    "                return \"No solution\"\n",
    "            return \"Infinite solutions\"\n",
    "        return f\"x={int((rightNumCount-leftNumCount)/(leftACount-rightACount))}\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        # 1. 等式分为两边 等号左边计入left 右边计入right\n",
    "        # 2. 建立left_num, left_x, right_num, right_x \n",
    "        index = equation.index('=')\n",
    "        def get_res(start, end, flag):\n",
    "            val_sum, val_x, num = 0, 0, 0\n",
    "            x_zero = -1\n",
    "            for i in range(start, end):\n",
    "                if equation[i] == 'x':\n",
    "                    #x系数不为0\n",
    "                    if x_zero != 0:\n",
    "                        val_x += num * flag if num else flag\n",
    "                    num = 0\n",
    "                elif equation[i] == '+':\n",
    "                    val_sum += flag * num\n",
    "                    num, flag = 0, 1\n",
    "                elif equation[i] == '-':\n",
    "                    val_sum += flag * num\n",
    "                    num, flag = 0 , -1\n",
    "                else:\n",
    "                    num =10 * num + int(equation[i])\n",
    "                    x_zero = num # 考虑x系数是否为0\n",
    "            val_sum += flag * num\n",
    "            return val_sum, val_x\n",
    "        sum_left, left_x = get_res(0, index, 1)\n",
    "        sum_right, right_x = get_res(index + 1, len(equation), 1)\n",
    "\n",
    "        if left_x == right_x and sum_left == sum_right:\n",
    "            return \"Infinite solutions\"\n",
    "        elif left_x == right_x and sum_left != sum_right:\n",
    "            return \"No solution\"\n",
    "        else:\n",
    "            return f'x={str((sum_right - sum_left) // (left_x - right_x))}'\n",
    "    \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        t1, t2 = equation.split('=')\n",
    "        if t2[0] not in '-+':\n",
    "            t2 = '+' + t2\n",
    "        t2 = list(t2)\n",
    "        for i in range(len(t2)):\n",
    "            if t2[i] == '+':\n",
    "                t2[i] = '-'\n",
    "            elif t2[i] == '-':\n",
    "                t2[i] = '+'\n",
    "\n",
    "        equation = t1 + ''.join(t2)\n",
    "        if equation[0] not in '-+':\n",
    "            equation = '+' + equation\n",
    "        x = 0\n",
    "        nums = 0\n",
    "\n",
    "        i = 0\n",
    "        n = len(equation)\n",
    "        while i < n:\n",
    "            k = 1 if equation[i] == '+' else -1\n",
    "            i += 1\n",
    "            if equation[i] == 'x':\n",
    "                x += 1 * k\n",
    "                i += 1 \n",
    "                continue\n",
    "\n",
    "            num = 0\n",
    "            while i < n and '0' <= equation[i] <= '9':\n",
    "                num = num * 10 + int(equation[i])\n",
    "                i += 1\n",
    "            if i < n and equation[i] == 'x':\n",
    "                x += num * k\n",
    "                i += 1\n",
    "            else:\n",
    "                nums += num * k\n",
    "\n",
    "        if x == 0 and nums == 0:\n",
    "            return \"Infinite solutions\"\n",
    "        if x == 0:\n",
    "            return \"No solution\"\n",
    "        if nums % x != 0:\n",
    "            return \"No solution\"\n",
    "        return \"x=%d\" % (-nums//x)\n",
    "        \n",
    "\n",
    "\n",
    "\n",
    "\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        left,right = equation.split('=')\n",
    "\n",
    "        def help(ins):\n",
    "            length = len(ins)\n",
    "            xnum = 0\n",
    "            num = 0\n",
    "            add = True\n",
    "            i = 0\n",
    "            if ins[0]=='-':\n",
    "                add = False\n",
    "                i+=1\n",
    "            while i<length:\n",
    "\n",
    "                s = i\n",
    "                while i<length and ins[i]!='+' and ins[i]!='-':\n",
    "                    i+=1\n",
    "                sub = ins[s:i]\n",
    "                if sub[-1]=='x':\n",
    "                    if add:\n",
    "                        if len(sub)==1:\n",
    "                            xnum += 1\n",
    "                        else:\n",
    "                            xnum += int(sub[:len(sub)-1])\n",
    "                    else:\n",
    "                        if len(sub)==1:\n",
    "                            xnum -= 1\n",
    "                        else:\n",
    "                            xnum -= int(sub[:len(sub)-1])\n",
    "                else:\n",
    "                    if add:\n",
    "                        num += int(sub)\n",
    "                    else:\n",
    "                        num -= int(sub)\n",
    "                pass\n",
    "\n",
    "                if i<length:\n",
    "                    add = True if ins[i]=='+' else False\n",
    "                i+=1\n",
    "            return num, xnum\n",
    "\n",
    "        lnum, lx = help(left)\n",
    "        rnum, rx = help(right)\n",
    "        xnum = lx - rx\n",
    "        res = rnum - lnum\n",
    "        if xnum==0 and res!=0:\n",
    "            return \"No solution\"\n",
    "        elif xnum==0 and res==0:\n",
    "            return \"Infinite solutions\"\n",
    "        else:\n",
    "            if res % xnum !=0:\n",
    "                return \"No solution\"\n",
    "            else:\n",
    "                return \"x={}\".format(res//xnum)\n",
    "        \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        left,right = equation.split('=')\n",
    "\n",
    "        def help(ins):\n",
    "            length = len(ins)\n",
    "            xnum = 0\n",
    "            num = 0\n",
    "            add = True\n",
    "            i = 0\n",
    "            if ins[0]=='-':\n",
    "                add = False\n",
    "                i+=1\n",
    "            while i<length:\n",
    "                s = i\n",
    "                while i<length and ins[i]!='+' and ins[i]!='-':\n",
    "                    i+=1\n",
    "                sub = ins[s:i]\n",
    "                if sub[-1]=='x':\n",
    "                    if add:\n",
    "                        if len(sub)==1:\n",
    "                            xnum += 1\n",
    "                        else:\n",
    "                            xnum += int(sub[:len(sub)-1])\n",
    "                    else:\n",
    "                        if len(sub)==1:\n",
    "                            xnum -= 1\n",
    "                        else:\n",
    "                            xnum -= int(sub[:len(sub)-1])\n",
    "                else:\n",
    "                    if add:\n",
    "                        num += int(sub)\n",
    "                    else:\n",
    "                        num -= int(sub)\n",
    "                pass\n",
    "\n",
    "                if i<length:\n",
    "                    add = True if ins[i]=='+' else False\n",
    "                i+=1\n",
    "            return num, xnum\n",
    "\n",
    "        lnum, lx = help(left)\n",
    "        rnum, rx = help(right)\n",
    "        xnum = lx - rx\n",
    "        res = rnum - lnum\n",
    "        if xnum==0 and res!=0:\n",
    "            return \"No solution\"\n",
    "        elif xnum==0 and res==0:\n",
    "            return \"Infinite solutions\"\n",
    "        else:\n",
    "            if res % xnum !=0:\n",
    "                return \"No solution\"\n",
    "            else:\n",
    "                return \"x={}\".format(res//xnum)\n",
    "        \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        idx = equation.index('=')\n",
    "        s1 = equation[:idx]\n",
    "        s2 = equation[idx+1:]\n",
    "        def f(s):\n",
    "            res = ctx = 0\n",
    "            if s[0].isdigit() or s[0]=='x':\n",
    "                s = '+' +s\n",
    "            n = len(s )\n",
    "            left,right = 0,1\n",
    "            dic ={'-':-1,'+':1}\n",
    "            while right<n:\n",
    "                if s[right]  in {'+','-'}:\n",
    "                    tmps = s[left:right]\n",
    "                    print(tmps)\n",
    "                    if 'x' in tmps:\n",
    "                        if len(tmps) == 2:\n",
    "                            ctx += dic[tmps[0]]*1\n",
    "                        else:\n",
    "                            ctx += int(tmps[:len(tmps)-1])\n",
    "                    else:\n",
    "                        res += int(tmps)\n",
    "                    left = right\n",
    "                    # right += 1\n",
    "                elif right == n-1:\n",
    "                    print('1')\n",
    "                    tmps = s[left:right+1]\n",
    "                    print(tmps)\n",
    "                    if 'x' in tmps:\n",
    "                        if len(tmps) == 2:\n",
    "                            ctx += dic[tmps[0]]*1\n",
    "                        else:\n",
    "                            ctx += int(tmps[:len(tmps)-1])\n",
    "                    else:\n",
    "                        res += int(tmps)\n",
    "                    \n",
    "                right += 1\n",
    "            print(res,ctx)\n",
    "            return res,ctx\n",
    "        res1,ctx1 = f(s1)\n",
    "        res2,ctx2 = f(s2)\n",
    "        he = res1 - res2\n",
    "        ctx = ctx1-ctx2\n",
    "        print(res1,ctx1)\n",
    "        if he == 0 and ctx == 0:\n",
    "            return \"Infinite solutions\"\n",
    "        elif he !=0 and ctx == 0:\n",
    "            return \"No solution\" \n",
    "        else:\n",
    "            return \"x=\"+ str(-1*(he//ctx))\n",
    "                \n",
    "\n",
    "                        \n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "        # def f(s,sign):\n",
    "        #     res = cnt = num = 0\n",
    "        #     sign2 = 1\n",
    "        #     n = len(s)\n",
    "        #     i = 0\n",
    "        #     while i<n:\n",
    "        #         if s[i] == '+':\n",
    "        #             sign2  = 1\n",
    "        #             i += 1\n",
    "        #             continue\n",
    "        #         if s[i] == '-':\n",
    "        #             sign2 = -1\n",
    "        #             i += 1\n",
    "        #             continue\n",
    "        #         while i<n and s[i].isdigit():\n",
    "        #             num = num*10 + int(s[i])\n",
    "        #             i += 1\n",
    "        #         if i<n and s[i] == 'x':\n",
    "        #             if i == 0 or (i>0 and not s[i-1].isdigit()):\n",
    "        #                 print(sign,sign2)\n",
    "        #                 cnt += sign*sign2\n",
    "        #             else:\n",
    "        #                 cnt += sign*sign2*num\n",
    "        #                 num = 0\n",
    "        #             sign2 = 1\n",
    "        #             i += 1\n",
    "        #         else:\n",
    "        #             res += sign*sign2*num\n",
    "        #             sign2 =1\n",
    "        #             num = 0\n",
    "        #     return res,cnt\n",
    "        res1,ctx1 = f(s1,1)\n",
    "        res2,ctx2 = f(s2,-1)\n",
    "        he = res1 + res2\n",
    "        ctx = ctx1+ctx2\n",
    "        print(res1,ctx1)\n",
    "        if he == 0 and ctx == 0:\n",
    "            return \"Infinite solutions\"\n",
    "        elif he !=0 and ctx == 0:\n",
    "            return \"No solution\" \n",
    "        else:\n",
    "            return \"x=\"+ str(-1*(he//ctx))\n",
    "                \n",
    " \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        def parse(s):\n",
    "            a,b=0,0#分别代表二者的系数\n",
    "            i,j=0,0\n",
    "            operand=''\n",
    "            while j<len(s):\n",
    "                while j<len(s) and s[j] not in '+-':\n",
    "                    j+=1\n",
    "                # tmp=s[i:j+1]\n",
    "                tmp=s[i:j]\n",
    "                # print(tmp)\n",
    "                # print('aa:',tmp[:-1])\n",
    "                if not tmp:continue\n",
    "                if tmp[-1]=='x':\n",
    "                    if tmp[:-1]=='-':a_tmp=-1\n",
    "                    else:a_tmp=int(tmp[:-1]) if tmp[:-1]!='' else 1\n",
    "                    if operand=='' or operand=='+':a+=a_tmp\n",
    "                    if operand=='-' :a-=a_tmp\n",
    "                else:\n",
    "                    if operand=='' or operand=='+':b+=int(tmp)\n",
    "                    if operand=='-':b-=int(tmp)\n",
    "                if j<len(s):operand=s[j]\n",
    "                i=j+1\n",
    "                j+=1\n",
    "            return a,b\n",
    "        part1=equation.strip().split('=')[0]\n",
    "        part2=equation.strip().split('=')[1]\n",
    "        if part1[0]in'+-':part1='0'+part1\n",
    "        if part2[0] in '+-':part2='0'+part2\n",
    "        a1,b1=parse(part1)\n",
    "        a2,b2=parse(part2)\n",
    "        print(a1,b1)\n",
    "        print(a2,b2)\n",
    "        if a1==a2 and b1==b2:return 'Infinite solutions'\n",
    "        if a1==a2 and b1!=b2:return 'No solution'\n",
    "        # return 'x='+str((b1-b2)/(a1-a2))\n",
    "        return 'x='+str(int((b1-b2)/(a2-a1)))\n",
    "            \n",
    "                \n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        # 1. 等式分为两边 等号左边计入left 右边计入right\n",
    "        # 2. 建立left_num, left_x, right_num, right_x \n",
    "        index = equation.index('=')\n",
    "        num, flag = 0, 1\n",
    "        left_stack, right_stack = [], []\n",
    "        left_x, right_x = 0, 0\n",
    "        x_zero = -1\n",
    "        for i in range(index):\n",
    "            if equation[i] == 'x':\n",
    "                if x_zero == 0:\n",
    "                    left_x = 0\n",
    "                else:\n",
    "                    left_x += num * flag if num else flag\n",
    "                num = 0\n",
    "            elif equation[i] == '+':\n",
    "                left_stack.append(flag * num)\n",
    "                num, flag = 0, 1\n",
    "            elif equation[i] == '-':\n",
    "                left_stack.append(flag * num)\n",
    "                num, flag = 0 , -1\n",
    "            else:\n",
    "                #数字\n",
    "                num =10 * num + int(equation[i])\n",
    "                x_zero = num   \n",
    "        if num:\n",
    "            left_stack.append(num * flag)\n",
    "        num, flag = 0, 1\n",
    "        x_zero = -1\n",
    "        for j in range(index + 1, len(equation)):\n",
    "            if equation[j] == 'x':\n",
    "                if x_zero == 0:\n",
    "                    right_x = 0\n",
    "                else:\n",
    "                    right_x += num * flag if num else flag\n",
    "                num = 0\n",
    "            elif equation[j] == '+':\n",
    "                right_stack.append(flag * num)\n",
    "                num, flag = 0, 1\n",
    "            elif equation[j] == '-':\n",
    "                right_stack.append(flag * num)\n",
    "                num, flag = 0 , -1\n",
    "            else:\n",
    "                #数字\n",
    "                num =10 * num + int(equation[j])\n",
    "                x_zero = num\n",
    "        if num:\n",
    "            right_stack.append(num * flag)\n",
    "        sum_left = sum(left_stack)\n",
    "        sum_right = sum(right_stack)\n",
    "        # print(left_x, right_x)\n",
    "        print(left_stack, right_stack)\n",
    "        if left_x == right_x and sum_left == sum_right:\n",
    "            return \"Infinite solutions\"\n",
    "        elif left_x == right_x and sum_left != sum_right:\n",
    "            return \"No solution\"\n",
    "        elif left_x > right_x:\n",
    "            return \"x=\" + str((sum_right - sum_left) // (left_x - right_x))\n",
    "        else:\n",
    "            return \"x=\" + str((sum_left - sum_right) // (right_x - left_x))\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveEquation(self, equation: str) -> str:\n",
    "        x=0\n",
    "        op=1\n",
    "        num=0\n",
    "\n",
    "        n=len(equation)\n",
    "        i=0\n",
    "        while i <= n-1:\n",
    "            if equation[i]=='+':\n",
    "                op=1\n",
    "                i+=1\n",
    "            elif equation[i]=='-':\n",
    "                op=-1\n",
    "                i+=1\n",
    "            elif equation[i]=='=':\n",
    "                op=1\n",
    "                x=-x\n",
    "                num=-num\n",
    "                i+=1\n",
    "            else:\n",
    "                j=i\n",
    "                while j<=n-1 and (equation[j]=='x' or '0'<=equation[j]<='9'):\n",
    "                    j+=1\n",
    "                if equation[j-1]=='x':\n",
    "                    if j-1>i:\n",
    "                        x = x+int(equation[i:j-1])*op\n",
    "                    else:\n",
    "                        x+=1*op\n",
    "                else:\n",
    "                    num+=int(equation[i:j])*op\n",
    "                \n",
    "                print(num)\n",
    "                print(x)\n",
    "                i=j\n",
    "\n",
    "        if x==0:\n",
    "            if num==0:\n",
    "                return \"Infinite solutions\"\n",
    "            else:\n",
    "                return \"No solution\"\n",
    "        else:\n",
    "            return \"x=\"+str(int(-num/x))\n",
    "\n",
    "            \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def mostPoints(self, questions: List[List[int]]) -> int:\n",
    "        # @functools.lru_cache(None)\n",
    "        store = defaultdict(int)\n",
    "        \n",
    "        def solve(start = 0):\n",
    "            if start >= len(questions):\n",
    "                return 0\n",
    "            point, brain = questions[start]\n",
    "            if start + brain + 1 not in store:\n",
    "                store[start + brain + 1] = solve(start + brain + 1)\n",
    "            if start + 1 not in store:\n",
    "                store[start + 1] = solve(start + 1)\n",
    "            return max(point + store[start + brain + 1], store[start + 1])\n",
    "        \n",
    "        return solve()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        self.backtracking(board)\n",
    "    def backtracking(self,board):\n",
    "        for i in range(len(board)):\n",
    "            for j in range(len(board[0])):\n",
    "                if board[i][j]!='.':\n",
    "                    continue\n",
    "                for k in range(1,10):\n",
    "                    if self.isvalid(i,j,k,board):\n",
    "                        board[i][j] = str(k)\n",
    "                        if self.backtracking(board):\n",
    "                            return True\n",
    "                        board[i][j] = '.'\n",
    "                return False\n",
    "        return True\n",
    "    def isvalid(self,row,col,val,board):\n",
    "        for i in range(9):\n",
    "            if board[row][i]==str(val):\n",
    "                return False\n",
    "        for j in range(9):\n",
    "            if board[j][col]==str(val):\n",
    "                return False\n",
    "        start_row = (row//3)*3\n",
    "        start_col = (col//3)*3\n",
    "        for i in range(start_row,start_row+3):\n",
    "            for j in range(start_col,start_col+3):\n",
    "                if board[i][j]==str(val):\n",
    "                    return False\n",
    "        return True\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        return main(board)\n",
    "\n",
    "def main(board):\n",
    "    sub_board = {}\n",
    "    row_board = {row: {1, 2, 3, 4, 5, 6, 7, 8, 9} for row in range(9)}\n",
    "    col_board = {col: {1, 2, 3, 4, 5, 6, 7, 8, 9} for col in range(9)}\n",
    "    entry = {}\n",
    "    for row_no in [0, 1, 2]:\n",
    "        for col_no in [0, 1, 2]:\n",
    "            sub_board_no = (row_no, col_no)\n",
    "            temp_set = {1, 2, 3, 4, 5, 6, 7, 8, 9}\n",
    "            for i in range(row_no * 3, row_no * 3 + 3):\n",
    "                for j in range(col_no * 3, col_no * 3 + 3):\n",
    "                    if board[i][j] != '.':\n",
    "                        temp_set.remove(int(board[i][j]))\n",
    "                        row_board[i].remove(int(board[i][j]))\n",
    "                        col_board[j].remove(int(board[i][j]))\n",
    "                    else:\n",
    "                        entry[(i, j)] = set()\n",
    "            sub_board[sub_board_no] = temp_set\n",
    "\n",
    "    for key in entry.keys():\n",
    "        i, j = key\n",
    "        entry[key] = row_board[i] & col_board[j] & sub_board[(i // 3, j // 3)]\n",
    "\n",
    "    input_params = []\n",
    "    for xy, val in entry.items():\n",
    "        line = [0, xy[0], xy[1]] + list(val)\n",
    "        line[0] = len(line)\n",
    "        heapq.heappush(input_params, line)    \n",
    "\n",
    "    result = search(input_params, {})\n",
    "    for (i, j), val in result.items():\n",
    "        board[i][j] = str(val)\n",
    "    return result\n",
    "\n",
    "def search(heap, record, d=0):\n",
    "    if len(heap) == 1:\n",
    "        i, j = heap[0][1], heap[0][2]\n",
    "        val = heap[0][3]\n",
    "        record[(i, j)] = val\n",
    "        return record\n",
    "    else:\n",
    "        item = heapq.heappop(heap)\n",
    "        i, j, val_list = item[1], item[2], item[3:]\n",
    "        for val in val_list:\n",
    "            new_heap = []\n",
    "            deadend = False  # this val is not valid\n",
    "\n",
    "            for this_item in heap:\n",
    "                x, y, tmp_val_set = this_item[1], this_item[2], this_item[3:]\n",
    "                if i//3 == x//3 and j//3 == y//3 and val in tmp_val_set:\n",
    "                    tmp_val_set.remove(val)\n",
    "\n",
    "                if i == x and val in tmp_val_set:\n",
    "                    tmp_val_set.remove(val)\n",
    "\n",
    "                if j == y and val in tmp_val_set:\n",
    "                    tmp_val_set.remove(val)\n",
    "\n",
    "                if not tmp_val_set:\n",
    "                    deadend = True\n",
    "                    break\n",
    "                else:\n",
    "                    heapq.heappush(new_heap, [len(tmp_val_set), x, y] + tmp_val_set)\n",
    "            \n",
    "            if deadend:\n",
    "                continue\n",
    "            else:\n",
    "                # all removals passed\n",
    "                new_record = copy.copy(record)\n",
    "                new_record[(i, j)] = val\n",
    "                res = search(new_heap, new_record, d+1)\n",
    "                if res is None:\n",
    "                    continue\n",
    "                else:\n",
    "                    return res\n",
    "        return None\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from typing import List\n",
    "\n",
    "class Array:\n",
    "\n",
    "    def createArray(*dimensions):\n",
    "        if len(dimensions) == 1:\n",
    "            return [0] * dimensions[0]\n",
    "        \n",
    "        a = []\n",
    "        for _ in range(dimensions[0]):\n",
    "            a.append(Array.createArray(*dimensions[1:]))\n",
    "        return a\n",
    "\n",
    "    def copyArray(array):\n",
    "        if not isinstance(array, list):\n",
    "            return array\n",
    "\n",
    "        a = []\n",
    "        for v in array:\n",
    "            a.append(Array.copyArray(v))\n",
    "        return a\n",
    "\n",
    "    def copyArrayTo(src, dst):\n",
    "        for i in range(len(dst)):\n",
    "            if isinstance(src[i], list) and isinstance(dst[i], list):\n",
    "                Array.copyArrayTo(src[i], dst[i])\n",
    "            else:\n",
    "                dst[i] = src[i]\n",
    "\n",
    "class Constraint:\n",
    "\n",
    "    def __init__(self, board: List[List[str]]) -> None:\n",
    "        self.rows = Array.createArray(9, 9)\n",
    "        self.columns = Array.createArray(9, 9)\n",
    "        self.boxes = Array.createArray(3, 3, 9)\n",
    "\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if isinstance(board[i][j], str) and board[i][j] != \".\":\n",
    "                    index = int(board[i][j]) - 1\n",
    "\n",
    "                    self.add(i, j, index)\n",
    "\n",
    "                    if self.isInvalid(i, j, index):\n",
    "                        print(\"The Sudoku can't be solved\")\n",
    "                        return\n",
    "\n",
    "    def isEmpty(self, i, j, index) -> bool:\n",
    "        return self.rows[i][index] == 0 and self.columns[j][index] == 0 and self.boxes[i // 3][j // 3][index] == 0\n",
    "\n",
    "    def isInvalid(self, i, j, index) -> bool:\n",
    "        return self.rows[i][index] > 1 or self.columns[j][index] > 1 or self.boxes[i // 3][j // 3][index] > 1\n",
    "\n",
    "    def add(self, i, j, index) -> None:\n",
    "        self.rows[i][index] += 1\n",
    "        self.columns[j][index] += 1\n",
    "        self.boxes[i // 3][j // 3][index] += 1\n",
    "\n",
    "class Rangement:\n",
    "\n",
    "    def __init__(self, board: List[List]) -> None:\n",
    "        self.rows = Array.createArray(9, 9)\n",
    "        self.columns = Array.createArray(9, 9)\n",
    "        self.boxes = Array.createArray(3, 3, 9)\n",
    "\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if isinstance(board[i][j], list):\n",
    "                    for k in range(len(board[i][j])):\n",
    "                        index = board[i][j][k] - 1\n",
    "\n",
    "                        self.rows[i][index] += 1\n",
    "                        self.columns[j][index] += 1\n",
    "                        self.boxes[i // 3][j // 3][index] += 1\n",
    "\n",
    "    def applyConstraint(self, board: List[List], i, j, constraint) -> bool:\n",
    "        if not isinstance(board[i][j], list):\n",
    "            return True\n",
    "\n",
    "        k = len(board[i][j]) - 1\n",
    "        while k >= 0:\n",
    "            index = board[i][j][k] - 1\n",
    "\n",
    "            if not constraint.isEmpty(i, j, index):\n",
    "                board[i][j].pop(k)\n",
    "                \n",
    "                self.rows[i][index] -= 1\n",
    "                self.columns[j][index] -= 1\n",
    "                self.boxes[i // 3][j // 3][index] -= 1\n",
    "\n",
    "            k -= 1\n",
    "        \n",
    "        return len(board[i][j]) > 0\n",
    "\n",
    "    def remove(self, i, j, index):\n",
    "        self.rows[i][index] -= 1\n",
    "        self.columns[j][index] -= 1\n",
    "        self.boxes[i // 3][j // 3][index] -= 1\n",
    "\n",
    "    def allowOneValue(self, i, j, index):\n",
    "        return self.rows[i][index] == 1 or self.columns[j][index] == 1 or self.boxes[i // 3][j // 3][index] == 1\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "\n",
    "        constraint = Constraint(board)\n",
    "\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if board[i][j] == \".\":\n",
    "                    board[i][j] = [index + 1 for index in range(9) if constraint.isEmpty(i, j, index)]\n",
    "\n",
    "        rangement = Rangement(board)\n",
    "\n",
    "        # print(board)\n",
    "        \n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if isinstance(board[i][j], list):\n",
    "                    self.applyConstraint(board, i, j, constraint, rangement)\n",
    "\n",
    "                    if isinstance(board[i][j], str):\n",
    "                        self.propagate(board, i, j, constraint, rangement)\n",
    "\n",
    "        self.solveR(board)\n",
    "    \n",
    "        # print()\n",
    "        # for i in range(9):\n",
    "        #     print(board[i])\n",
    "\n",
    "    def propagate(self, board, r, c, constraint: Constraint, rangement: Rangement):\n",
    "        for i in range(9):\n",
    "            j = c\n",
    "            if isinstance(board[i][j], list):\n",
    "                if not self.applyConstraint(board, i, j, constraint, rangement):\n",
    "                    return False\n",
    "\n",
    "                if isinstance(board[i][j], str):\n",
    "                    if not self.propagate(board, i, j,constraint, rangement):\n",
    "                        return False\n",
    "\n",
    "        for j in range(9):\n",
    "            i = r\n",
    "            if isinstance(board[i][j], list):\n",
    "                if not self.applyConstraint(board, i, j,constraint, rangement):\n",
    "                    return False\n",
    "\n",
    "                if isinstance(board[i][j], str):\n",
    "                    if not self.propagate(board, i, j,constraint, rangement):\n",
    "                        return False\n",
    "\n",
    "        for i in range(r // 3, r // 3 + 3):\n",
    "            for j in range(c // 3, c // 3 + 3):\n",
    "                if isinstance(board[i][j], list):\n",
    "                    if not self.applyConstraint(board, i, j,constraint, rangement):\n",
    "                        return False\n",
    "\n",
    "                    if isinstance(board[i][j], str):\n",
    "                        if not self.propagate(board, i, j,constraint, rangement):\n",
    "                            return False\n",
    "\n",
    "        return True\n",
    "\n",
    "    def applyConstraint(self, board, i, j, constraint: Constraint, rangement: Rangement):\n",
    "        if not isinstance(board[i][j], list):\n",
    "            return True\n",
    "\n",
    "        if not rangement.applyConstraint(board, i, j, constraint):\n",
    "            return False\n",
    "\n",
    "        if len(board[i][j]) == 1:\n",
    "            index = board[i][j][0] - 1\n",
    "            board[i][j] = str(index + 1)\n",
    "\n",
    "            constraint.add(i, j, index)\n",
    "            rangement.remove(i, j, index)\n",
    "            return True\n",
    "            \n",
    "        k = len(board[i][j]) - 1\n",
    "        while k >= 0:\n",
    "            index = board[i][j][k] - 1\n",
    "\n",
    "            if rangement.allowOneValue(i, j, index):\n",
    "                break\n",
    "            \n",
    "            k -= 1\n",
    "\n",
    "        if k >= 0:\n",
    "            lst = board[i][j]\n",
    "\n",
    "            index = board[i][j][k] - 1\n",
    "            board[i][j] = str(index + 1)\n",
    "                \n",
    "            constraint.add(i, j, index)\n",
    "\n",
    "            for t in range(len(lst)):\n",
    "                index = lst[t] - 1\n",
    "                rangement.remove(i, j, index)\n",
    "\n",
    "        return True\n",
    "        \n",
    "    def solveR(self, board: List[List]) -> None:\n",
    "        # newboard = Array.copyArray(board)\n",
    "        \n",
    "        jumpOut = False\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if isinstance(board[i][j], list):\n",
    "                    \n",
    "                    k = len(board[i][j]) - 1\n",
    "                    while k >= 0:\n",
    "                        index = board[i][j][k] - 1\n",
    "\n",
    "                        newboard = Array.copyArray(board)\n",
    "                        c = Constraint(newboard)\n",
    "                        r = Rangement(newboard)\n",
    "\n",
    "                        newboard[i][j] = str(index + 1)\n",
    "                        c.add(i, j, index)\n",
    "                        r.remove(i, j, index)\n",
    "                        \n",
    "                        if not self.propagate(newboard, i, j, c, r):\n",
    "                            k -= 1\n",
    "                            continue\n",
    "                        \n",
    "                        if not self.solveR(newboard):\n",
    "                            return False\n",
    "\n",
    "                        k -= 1\n",
    "                        break\n",
    "\n",
    "                    for i in range(9):\n",
    "                        for j in range(9):\n",
    "                            board[i][j] = newboard[i][j]\n",
    "\n",
    "                    jumpOut = True\n",
    "                    return True\n",
    "\n",
    "            if jumpOut:\n",
    "                break\n",
    "\n",
    "        return True\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        def pre():\n",
    "            self.row = [set() for i in range(9)]\n",
    "            self.line = [set() for i in range(9)]\n",
    "            self.block = [set() for i in range(9)]\n",
    "            self.record = dict()\n",
    "            for i in range(9):\n",
    "                for j in range(9):\n",
    "                    if board[i][j] == '.':\n",
    "                        continue\n",
    "                    self.row[j].add(board[i][j])\n",
    "                    self.line[i].add(board[i][j])\n",
    "                    self.block[i // 3 * 3+ j // 3].add(board[i][j])\n",
    "            for i in range(9):\n",
    "                for j in range(9):\n",
    "                    if board[i][j] != '.':\n",
    "                        continue\n",
    "                    possible = set([str(_) for _ in range(1, 10)]) - self.row[j] - self.line[i] - self.block[i // 3 * 3+ j // 3] \n",
    "                    self.record[str(len(possible))+str(i)+str(j)] = possible\n",
    "            return\n",
    "\n",
    "        def back_track():\n",
    "            if not self.record:\n",
    "                return True\n",
    "            cur = min(self.record)\n",
    "            for candidate in self.record[cur]:\n",
    "                x = int(cur[1])\n",
    "                y = int(cur[2])\n",
    "                record_copy = deepcopy(self.record)\n",
    "                for one in self.record:\n",
    "                    if one == cur:\n",
    "                        continue\n",
    "                    x1, y1 = int(one[1]), int(one[2])\n",
    "                    if x1 == x or y1 == y or x1 //3 *3 + y1//3 == x //3 *3 + y //3:\n",
    "                        tmp = record_copy.pop(one)\n",
    "                        if candidate in tmp:\n",
    "                            tmp.remove(candidate)\n",
    "                        record_copy[str(len(tmp))+str(x1)+str(y1)] = tmp\n",
    "                record_copy, self.record = self.record, record_copy\n",
    "                board[x][y] = candidate\n",
    "                self.record.pop(cur)\n",
    "                if back_track():\n",
    "                    return True\n",
    "                else:\n",
    "                    self.record = record_copy\n",
    "                    board[x][y] = '.'\n",
    "        pre()\n",
    "        back_track()\n",
    "        \n",
    "\n",
    "            \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        def get_all_possible(nums, i_row, i_column):\n",
    "            all_num = set(str(n) for n in range(1, 10))\n",
    "            left = set(nums[i_row]).union(set([row[i_column] for row in nums]))\n",
    "            row, column = i_row // 3, i_column // 3\n",
    "            for v in range(3):\n",
    "                left = left.union(set(nums[row * 3 + v][column * 3: (column + 1) * 3]))\n",
    "            return sorted(all_num.difference(left))\n",
    "\n",
    "        def is_solved(sudoku):\n",
    "            for row in sudoku:\n",
    "                if '.' in row:\n",
    "                    return False\n",
    "            return True\n",
    "\n",
    "        def try_possible(sudoku, p_v=None, i_row=-1, i_column=-1):\n",
    "            if p_v:\n",
    "                sudoku[i_row][i_column] = p_v\n",
    "\n",
    "            p_dict, p_len = {}, {}\n",
    "            for i in range(9):\n",
    "                for j in range(9):\n",
    "                    if sudoku[i][j] == '.':\n",
    "                        p = get_all_possible(sudoku, i, j)\n",
    "                        if len(p) == 0:\n",
    "                            return False\n",
    "                        if len(p) == 1:\n",
    "                            return try_possible(sudoku, p.pop(), i, j)\n",
    "                        p_dict[(i, j)] = p\n",
    "                        p_len.setdefault(len(p), set()).add((i, j))\n",
    "\n",
    "            if not p_len and not p_dict and is_solved(sudoku):\n",
    "                return True\n",
    "\n",
    "            p_dict = sorted(p_dict.items(), key=lambda x: len(x[1]))\n",
    "            for index, values in p_dict:\n",
    "                for v in values:\n",
    "                    row, column = index\n",
    "                    sudoku_copy = [nums[:] for nums in sudoku]\n",
    "                    if try_possible(sudoku_copy, v, row, column):\n",
    "                        for r in range(9):\n",
    "                            for c in range(9):\n",
    "                                sudoku[r][c] = sudoku_copy[r][c]\n",
    "                        return True\n",
    "                return False\n",
    "\n",
    "            return True if is_solved(sudoku) else False\n",
    "\n",
    "        try_possible(board)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        # 行记录\n",
    "        self.hmap = []\n",
    "        # 列记录\n",
    "        self.lmap = []\n",
    "        # 分图记录\n",
    "        self.tmap = []\n",
    "        for i in range(9):\n",
    "            self.hmap.append([])\n",
    "            self.lmap.append([])\n",
    "            self.tmap.append([])\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if board[i][j] != '.':\n",
    "                    self.hmap[i].append(board[i][j])\n",
    "                    self.lmap[j].append(board[i][j])\n",
    "                    p = i // 3 * 3 + (j // 3)\n",
    "                    self.tmap[p].append(board[i][j])\n",
    "        self.playdSudoku(board)\n",
    "\n",
    "    def playdSudoku(self, board) -> bool:\n",
    "        key = []\n",
    "        asr = []\n",
    "        is_slave = False\n",
    "        slaves = []\n",
    "        for i in board:\n",
    "            key.append(i[:])\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if key[i][j] == '.':\n",
    "                    l = i // 3 * 3 + (j // 3)\n",
    "                    key[i][j] = []\n",
    "                    for k in range(1, 10):\n",
    "                        k = str(k)\n",
    "                        if k not in self.hmap[i] and k not in self.lmap[j] and k not in self.tmap[l]:\n",
    "                            key[i][j].append(k)\n",
    "                    if key[i][j] == []:\n",
    "                        return False\n",
    "                    elif len(key[i][j]) == 1:\n",
    "                        k = key[i][j][0]\n",
    "                        slaves.append([i, j, k])\n",
    "                        is_slave = True\n",
    "                    elif asr != [] and len(key[i][j]) < len(key[asr[0][0]][asr[0][1]]):\n",
    "                        asr.insert(0, [i, j])\n",
    "                    else:\n",
    "                        asr.append([i, j])\n",
    "                # 根据必须存在一个值确定一个一定对的值\n",
    "        for i, j in asr:\n",
    "            l_a = len(key[i][j])\n",
    "            if l_a > 1:\n",
    "                key_t = False\n",
    "                # 判断横行\n",
    "                for ki in key[i][j]:\n",
    "                    key_t = False\n",
    "                    for m in range(9):\n",
    "                        if m == j:\n",
    "                            continue\n",
    "                        if type(key[i][m]) == list:\n",
    "                            if ki in key[i][m] and len(key[i][m]) > 1:\n",
    "                                key_t = True\n",
    "                                break\n",
    "                            if ki in key[i][m] and len(key[i][m]) == 1:\n",
    "                                key[i][j].remove(ki)\n",
    "                                key_t = True\n",
    "                                break\n",
    "                    if key_t:\n",
    "                        continue\n",
    "                    for m in range(9):\n",
    "                        if m == j:\n",
    "                            continue\n",
    "                        if type(key[m][j]) == list:\n",
    "                            if ki in key[m][j] and len(key[m][j]) > 1:\n",
    "                                key_t = True\n",
    "                                break\n",
    "                            if ki in key[m][j] and len(key[m][j]) == 1:\n",
    "                                key[i][j].remove(ki)\n",
    "                                key_t = True\n",
    "                                break\n",
    "                    if key_t:\n",
    "                        continue\n",
    "                    m1 = i // 3 * 3\n",
    "                    n1 = j // 3 * 3\n",
    "                    for m in range(m1, m1 + 3):\n",
    "                        for n in range(n1, n1 + 3):\n",
    "                            if m == j and n == j:\n",
    "                                continue\n",
    "                            if type(key[m][j]) == list:\n",
    "                                if ki in key[m][n] and len(key[m][n]) > 1:\n",
    "                                    key_t = True\n",
    "                                    break\n",
    "                                if ki in key[m][n] and len(key[m][n]) == 1:\n",
    "                                    key[i][j].remove(ki)\n",
    "                                    key_t = True\n",
    "                                    break\n",
    "                    if key_t:\n",
    "                        continue\n",
    "                    key_t = ki\n",
    "                    break\n",
    "                if type(key_t) == str:\n",
    "                    is_slave = True\n",
    "                    key[i][j] == [key_t]\n",
    "                    slaves.append([i, j, key_t])                \n",
    "        if is_slave:\n",
    "            i, j, k = slaves[0]\n",
    "            l = i // 3 * 3 + (j // 3)\n",
    "            board[i][j] = k\n",
    "            self.hmap[i].append(k)\n",
    "            self.lmap[j].append(k)\n",
    "            self.tmap[l].append(k)\n",
    "\n",
    "            if self.playdSudoku(board):\n",
    "                return True\n",
    "            else:\n",
    "                i, j, k = slaves[0]\n",
    "                l = i // 3 * 3 + (j // 3)\n",
    "                self.lmap[j].remove(k)\n",
    "                self.hmap[i].remove(k)\n",
    "                self.tmap[l].remove(k)\n",
    "                board[i][j] = '.'\n",
    "        elif asr == []:\n",
    "            return True\n",
    "        else:\n",
    "            i, j = asr[0]\n",
    "            for k in key[i][j]:\n",
    "                board[i][j] = k\n",
    "                self.hmap[i].append(k)\n",
    "                self.lmap[j].append(k)\n",
    "                l = i // 3 * 3 + (j // 3)\n",
    "                self.tmap[l].append(k)\n",
    "                if self.playdSudoku(board):\n",
    "                    return True\n",
    "                else:\n",
    "                    self.lmap[j].pop(-1)\n",
    "                    self.hmap[i].pop(-1)\n",
    "                    self.tmap[l].pop(-1)\n",
    "                    board[i][j] = '.'\n",
    "        return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class DLX:\r\n",
    "    \"\"\"\r\n",
    "    十字交叉双向循环链表\r\n",
    "    \"\"\"\r\n",
    "\r\n",
    "    def __init__(self, n):\r\n",
    "        \"\"\"\r\n",
    "        :param n: 数独的阶数\r\n",
    "        \"\"\"\r\n",
    "        self.n = n\r\n",
    "        self.m = n ** 2 * n ** 2 * 4 + 1  # 总共的列数(标注节点数+头节点)\r\n",
    "        self.max_nums = n ** 2 * n ** 2 * n ** 2 * 4 + self.m  # 最大节点编号\r\n",
    "\r\n",
    "        # 用下标表示节点编号，下标0表示节点0（即头节点），下标1表示节点1，以此类推...\r\n",
    "        self.u = [0 for _ in range(self.max_nums)]  # 记录节点的上链接点\r\n",
    "        self.d = [0 for _ in range(self.max_nums)]  # 记录节点的下链接点\r\n",
    "        self.l = [0 for _ in range(self.max_nums)]  # 记录节点的左链接点\r\n",
    "        self.r = [0 for _ in range(self.max_nums)]  # 记录节点的右链接点\r\n",
    "        self.row = [0 for _ in range(self.max_nums)]  # 记录节点所在的行\r\n",
    "        self.col = [0 for _ in range(self.max_nums)]  # 记录节点所在的列\r\n",
    "\r\n",
    "        # 设置首行的上下左右链接关系\r\n",
    "        for i in range(self.m):\r\n",
    "            self.u[i] = i\r\n",
    "            self.d[i] = i\r\n",
    "            self.r[i] = i + 1\r\n",
    "            self.l[i] = i - 1\r\n",
    "            self.row[i] = 0\r\n",
    "            self.col[i] = i\r\n",
    "        self.head = 0\r\n",
    "        self.l[self.head] = self.m - 1\r\n",
    "        self.r[self.m - 1] = self.head\r\n",
    "\r\n",
    "        self.s = [0 for _ in range(self.m)]  # 记录每列节点个数，以便搜索时选择节点数最少的列删除（即优化搜索方向）\r\n",
    "\r\n",
    "        self.next_point = self.m  # 下一个节点编号\r\n",
    "\r\n",
    "        self.ans = [0 for _ in range(n ** 2 * n ** 2 * n ** 2)]  # 所有答案的集合\r\n",
    "        self.end = 0\r\n",
    "\r\n",
    "    def add_row(self, row, columns):\r\n",
    "        \"\"\"\r\n",
    "        :param row: 新增节点所在的行\r\n",
    "        :param columns: 新增节点所在的列\r\n",
    "        :return:\r\n",
    "        \"\"\"\r\n",
    "        first = self.next_point\r\n",
    "        self.l[first] = first\r\n",
    "        self.r[first] = first\r\n",
    "\r\n",
    "        for c in columns:\r\n",
    "            # 先增加新节点对上下左右节点的指向\r\n",
    "            self.u[self.next_point] = self.u[c]\r\n",
    "            self.d[self.next_point] = c\r\n",
    "            self.l[self.next_point] = self.l[first]\r\n",
    "            self.r[self.next_point] = first\r\n",
    "            self.row[self.next_point] = row\r\n",
    "            self.col[self.next_point] = c\r\n",
    "\r\n",
    "            # 然后修改上下左右节点的指向，即指向新节点\r\n",
    "            self.r[self.l[first]] = self.next_point\r\n",
    "            self.l[first] = self.next_point\r\n",
    "            self.d[self.u[c]] = self.next_point\r\n",
    "            self.u[c] = self.next_point\r\n",
    "\r\n",
    "            self.s[c] += 1  # 该列节点数+1\r\n",
    "\r\n",
    "            self.next_point += 1  # 节点编号+1\r\n",
    "\r\n",
    "    def remove(self, c):\r\n",
    "        \"\"\"\r\n",
    "        删除第c列\r\n",
    "        :param c:\r\n",
    "        :return:\r\n",
    "        \"\"\"\r\n",
    "        self.l[self.r[c]] = self.l[c]\r\n",
    "        self.r[self.l[c]] = self.r[c]\r\n",
    "\r\n",
    "        i = self.d[c]\r\n",
    "        while i != c:\r\n",
    "            j = self.r[i]\r\n",
    "            while j != i:\r\n",
    "                self.d[self.u[j]] = self.d[j]\r\n",
    "                self.u[self.d[j]] = self.u[j]\r\n",
    "                self.s[self.col[j]] -= 1\r\n",
    "                j = self.r[j]\r\n",
    "            i = self.d[i]\r\n",
    "\r\n",
    "    def restore(self, c):\r\n",
    "        \"\"\"\r\n",
    "        恢复第c列\r\n",
    "        :param c:\r\n",
    "        :return:\r\n",
    "        \"\"\"\r\n",
    "        i = self.u[c]\r\n",
    "        while i != c:\r\n",
    "            j = self.l[i]\r\n",
    "            while j != i:\r\n",
    "                self.d[self.u[j]] = j\r\n",
    "                self.u[self.d[j]] = j\r\n",
    "                self.s[self.col[j]] += 1\r\n",
    "                j = self.l[j]\r\n",
    "            i = self.u[i]\r\n",
    "        self.l[self.r[c]] = c\r\n",
    "        self.r[self.l[c]] = c\r\n",
    "\r\n",
    "    def dance(self, step):\r\n",
    "        \"\"\"\r\n",
    "        :param step: 递归深度\r\n",
    "        :return:\r\n",
    "        \"\"\"\r\n",
    "        if self.r[self.head] == self.head:\r\n",
    "            self.end = step\r\n",
    "            return True\r\n",
    "\r\n",
    "        c = self.r[self.head]\r\n",
    "        j = self.r[self.head]\r\n",
    "        # 选择节点数最少的列\r\n",
    "        while j != self.head:\r\n",
    "            if self.s[j] < self.s[c]:\r\n",
    "                c = j\r\n",
    "            j = self.r[j]\r\n",
    "        self.remove(c)\r\n",
    "\r\n",
    "        i = self.d[c]\r\n",
    "        while i != c:\r\n",
    "            # 删除节点i所在的行，并将其保存到结果集中\r\n",
    "            self.ans[step] = self.row[i]\r\n",
    "            j = self.r[i]\r\n",
    "            while j != i:\r\n",
    "                self.remove(self.col[j])\r\n",
    "                j = self.r[j]\r\n",
    "            if self.dance(step + 1):  # 搜索成功则返回\r\n",
    "                return True\r\n",
    "\r\n",
    "            # 搜索失败，要恢复，回溯\r\n",
    "            self.ans[step] = 0\r\n",
    "            j = self.l[i]\r\n",
    "            while j != i:\r\n",
    "                self.restore(self.col[j])\r\n",
    "                j = self.l[j]\r\n",
    "\r\n",
    "            i = self.d[i]\r\n",
    "        self.restore(c)\r\n",
    "        return False\r\n",
    "\r\n",
    "    def transform_input(self, i, j, num):\r\n",
    "        c1 = self.n ** 2 * (i - 1) + j\r\n",
    "        c2 = self.n ** 2 * self.n ** 2 + self.n ** 2 * (i - 1) + num\r\n",
    "        c3 = self.n ** 2 * self.n ** 2 * 2 + self.n ** 2 * (j - 1) + num\r\n",
    "        c4 = self.n ** 2 * self.n ** 2 * 3 + self.n ** 2 * ((i - 1) // self.n * self.n + (j - 1) // self.n) + num\r\n",
    "        return c1, c2, c3, c4\r\n",
    "\r\n",
    "    def run(self, input_str):\r\n",
    "        input_matrix = []\r\n",
    "        row_index = 1\r\n",
    "        for i in range(1, self.n ** 2 + 1):\r\n",
    "            for j in range(1, self.n ** 2 + 1):\r\n",
    "                if input_str[i - 1][j - 1] != '.':\r\n",
    "                    tmp = int(input_str[i - 1][j - 1])\r\n",
    "                    input_matrix.append((i, j, tmp))\r\n",
    "                    self.add_row(row_index, self.transform_input(i, j, tmp))\r\n",
    "                    row_index += 1\r\n",
    "                else:\r\n",
    "                    for k in range(1, self.n ** 2 + 1):\r\n",
    "                        input_matrix.append((i, j, k))\r\n",
    "                        self.add_row(row_index, self.transform_input(i, j, k))\r\n",
    "                        row_index += 1\r\n",
    "\r\n",
    "        if self.dance(0):\r\n",
    "            for i in self.ans[:self.end]:\r\n",
    "                input_str[input_matrix[i - 1][0] - 1][input_matrix[i - 1][1] - 1] = str(input_matrix[i - 1][2])\r\n",
    "        else:\r\n",
    "            print('Impossible')\r\n",
    "\r\n",
    "class Solution:\r\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\r\n",
    "        dlx = DLX(3)\r\n",
    "        dlx.run(board)\r\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        def backtracking(board):\n",
    "            for i in range(len(board)):\n",
    "                for j in range(len(board[0])):\n",
    "                    if board[i][j] != '.':\n",
    "                        continue\n",
    "                    for k in range(1,10):\n",
    "                        if isValid(i,j,k,board):\n",
    "                            board[i][j] = str(k)\n",
    "                            if backtracking(board):\n",
    "                                return True\n",
    "                        board[i][j] = '.'\n",
    "                    return False\n",
    "            return True\n",
    "        \n",
    "        def isValid(row,col,val,board):\n",
    "            for i in range(9):\n",
    "                if board[i][col] == str(val):\n",
    "                    return False\n",
    "            \n",
    "            for j in range(9):\n",
    "                if board[row][j] == str(val):\n",
    "                    return False\n",
    "\n",
    "            start_row = (row//3)*3\n",
    "            start_col = (col//3)*3\n",
    "            for i in range(start_row,start_row+3):\n",
    "                for j in range(start_col,start_col+3):\n",
    "                    if board[i][j] == str(val):\n",
    "                        return False\n",
    "            return True\n",
    "\n",
    "        backtracking(board)\n",
    "        \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "import copy\n",
    "class Solution:\n",
    "    def __init__(self):\n",
    "        self.board = None\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        all_set = set([\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"])\n",
    "        col_set = [copy.deepcopy(all_set) for i in range(9)]  #可用的数\n",
    "        row_set = [copy.deepcopy(all_set) for i in range(9)]\n",
    "        quare_set = [copy.deepcopy(all_set) for i in range(9)]\n",
    "        # print(row_set[0])\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if board[i][j] != \".\":\n",
    "                    # print(board[i][j])\n",
    "                    row_set[i].remove(board[i][j])\n",
    "                    col_set[j].remove(board[i][j])\n",
    "                    quare_set[i // 3 * 3 + j // 3].remove(board[i][j])\n",
    "        \n",
    "        #########先使用简单的确定性填法######\n",
    "        while True:\n",
    "            change = 0\n",
    "            for i in range(9):\n",
    "                for j in range(9):\n",
    "                    use_set = row_set[i] & col_set[j] & quare_set[i // 3 * 3 + j // 3]\n",
    "                    if board[i][j] == \".\" and len(use_set) == 1:\n",
    "                        specific_num = list(use_set)[0]\n",
    "                        board[i][j] = specific_num\n",
    "                        row_set[i].remove(specific_num)\n",
    "                        col_set[j].remove(specific_num)\n",
    "                        quare_set[i // 3 * 3 + j // 3].remove(specific_num)\n",
    "                        change += 1\n",
    "            if change == 0:\n",
    "                break\n",
    "\n",
    "        self.board = board\n",
    "        self.search(0, 0, col_set, row_set, quare_set)\n",
    "        return self.board\n",
    "    \n",
    "    def search(self, i, j, col_set, row_set, quare_set):\n",
    "        if i == 9:\n",
    "            return True\n",
    "        if self.board[i][j] != \".\":\n",
    "            if j == 8:\n",
    "                is_yes = self.search(i + 1, 0, col_set, row_set, quare_set)\n",
    "            else:\n",
    "                is_yes = self.search(i, j + 1, col_set, row_set, quare_set)\n",
    "            return is_yes\n",
    "        \n",
    "        use_set = row_set[i] & col_set[j] & quare_set[i // 3 * 3 + j // 3] #并集\n",
    "        for num in use_set:\n",
    "            self.board[i][j] = num\n",
    "            col_set_copy = copy.deepcopy(col_set)\n",
    "            row_set_copy = copy.deepcopy(row_set)\n",
    "            quare_set_copy = copy.deepcopy(quare_set)\n",
    "\n",
    "            col_set_copy[j].remove(num)\n",
    "            row_set_copy[i].remove(num)\n",
    "            quare_set_copy[i // 3 * 3 + j // 3].remove(num)\n",
    "\n",
    "            if j == 8:\n",
    "                is_yes = self.search(i + 1, 0, col_set_copy, row_set_copy, quare_set_copy)\n",
    "            else:\n",
    "                is_yes = self.search(i, j + 1, col_set_copy, row_set_copy, quare_set_copy)\n",
    "            \n",
    "            if is_yes:\n",
    "                return True\n",
    "            \n",
    "            self.board[i][j] = \".\"\n",
    "        return False\n",
    "\n",
    "\n",
    "        \n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        # 行记录\n",
    "        self.hmap = []\n",
    "        # 列记录\n",
    "        self.lmap = []\n",
    "        # 分图记录\n",
    "        self.tmap = []\n",
    "        for i in range(9):\n",
    "            self.hmap.append([])\n",
    "            self.lmap.append([])\n",
    "            self.tmap.append([])\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if board[i][j] != '.':\n",
    "                    self.hmap[i].append(board[i][j])\n",
    "                    self.lmap[j].append(board[i][j])\n",
    "                    p = i // 3 * 3 + (j // 3)\n",
    "                    self.tmap[p].append(board[i][j])\n",
    "        self.playdSudoku(board)\n",
    "\n",
    "    def playdSudoku(self, board) -> bool:\n",
    "        key = []\n",
    "        asr = []\n",
    "        is_slave = False\n",
    "        slaves = []\n",
    "        for i in board:\n",
    "            key.append(i[:])\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if key[i][j] == '.':\n",
    "                    l = i // 3 * 3 + (j // 3)\n",
    "                    key[i][j] = []\n",
    "                    for k in range(1, 10):\n",
    "                        k = str(k)\n",
    "                        if k not in self.hmap[i] and k not in self.lmap[j] and k not in self.tmap[l]:\n",
    "                            key[i][j].append(k)\n",
    "                    if key[i][j] == []:\n",
    "                        return False\n",
    "                    elif len(key[i][j]) == 1:\n",
    "                        k = key[i][j][0]\n",
    "                        slaves.append([i, j, k])\n",
    "                        is_slave = True\n",
    "                    elif asr != [] and len(key[i][j]) < len(key[asr[0][0]][asr[0][1]]):\n",
    "                        asr.insert(0, [i, j])\n",
    "                    else:\n",
    "                        asr.append([i, j])\n",
    "        if is_slave:\n",
    "            i, j, k = slaves[0]\n",
    "            l = i // 3 * 3 + (j // 3)\n",
    "            board[i][j] = k\n",
    "            self.hmap[i].append(k)\n",
    "            self.lmap[j].append(k)\n",
    "            self.tmap[l].append(k)\n",
    "\n",
    "            if self.playdSudoku(board):\n",
    "                return True\n",
    "            else:\n",
    "                i, j, k = slaves[0]\n",
    "                l = i // 3 * 3 + (j // 3)\n",
    "                self.lmap[j].remove(k)\n",
    "                self.hmap[i].remove(k)\n",
    "                self.tmap[l].remove(k)\n",
    "                board[i][j] = '.'\n",
    "        elif asr == []:\n",
    "            return True\n",
    "        else:\n",
    "            i, j = asr[0]\n",
    "            for k in key[i][j]:\n",
    "                board[i][j] = k\n",
    "                self.hmap[i].append(k)\n",
    "                self.lmap[j].append(k)\n",
    "                l = i // 3 * 3 + (j // 3)\n",
    "                self.tmap[l].append(k)\n",
    "                if self.playdSudoku(board):\n",
    "                    return True\n",
    "                else:\n",
    "                    self.lmap[j].pop(-1)\n",
    "                    self.hmap[i].pop(-1)\n",
    "                    self.tmap[l].pop(-1)\n",
    "                    board[i][j] = '.'\n",
    "        return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "import copy\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "\n",
    "        def get_csp(pr, pc):\n",
    "            temp = copy.deepcopy(options)\n",
    "            for i in range(9):\n",
    "                if board[pr][i] in temp:\n",
    "                    temp.remove(str(board[pr][i]))\n",
    "                if board[i][pc] in temp:\n",
    "                    temp.remove(board[i][pc])\n",
    "            i_r, i_c = pr // 3 * 3, pc // 3 * 3\n",
    "            for i in range(3):\n",
    "                for j in range(3):\n",
    "                    if board[i_r + i][i_c + j] in temp:\n",
    "                        temp.remove(board[i_r + i][i_c + j])\n",
    "            return temp\n",
    "\n",
    "        def csp_update(pr, pc, csp):\n",
    "            for i in range(9):\n",
    "                if i > pc and (pr, i) in csp and board[pr][pc] in csp[pr, i]:\n",
    "                    csp[pr, i].remove(board[pr][pc])\n",
    "                    if len(csp[pr, i]) == 0:\n",
    "                        return False, {}\n",
    "                if i > pr and (i, pc) in csp and board[pr][pc] in csp[i, pc]:\n",
    "                    csp[i, pc].remove(board[pr][pc])\n",
    "                    if len(csp[i, pc]) == 0:\n",
    "                        return False, {}\n",
    "            i_r, i_c = pr // 3 * 3, pc // 3 * 3\n",
    "            for i in range(3):\n",
    "                for j in range(3):\n",
    "                    if (i > pr or j > pc) and (i_r + i, i_c + j) in csp and board[pr][pc] in csp[i_r + i, i_c + j]:\n",
    "                        csp[i_r + i, i_c + j].remove(board[pr][pc])\n",
    "                        if len(csp[i_r + i, i_c + j]) == 0:\n",
    "                            return False, {}\n",
    "            return True, csp\n",
    "\n",
    "        def solve(p, csp):\n",
    "            if p == len(csp_index):\n",
    "                return True\n",
    "            pr, pc = csp_index[p]\n",
    "            for i in csp[pr, pc]:\n",
    "                board[pr][pc] = i\n",
    "                flag, csp_temp = csp_update(pr, pc, copy.deepcopy(csp))\n",
    "                if flag:\n",
    "                    if solve(p + 1, csp_temp):\n",
    "                        return True\n",
    "                    else:\n",
    "                        board[pr][pc] = '.'\n",
    "                else:\n",
    "                    board[pr][pc] = '.'\n",
    "            return False\n",
    "\n",
    "        options = {str(x) for x in range(1, 10)}\n",
    "        csp = {}\n",
    "        csp_index = []\n",
    "        # initial csp\n",
    "        count = 0\n",
    "        for pr in range(9):\n",
    "            for pc in range(9):\n",
    "                if board[pr][pc] == '.':\n",
    "                    csp_index.append((pr, pc))\n",
    "                    csp[pr, pc] = get_csp(pr, pc)\n",
    "                    count += 1\n",
    "\n",
    "        flag = solve(0, csp)\n",
    "\n",
    "        return board\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        def copy(board1, board_):\n",
    "            for _i in range(9):\n",
    "                for _j in range(9):\n",
    "                    board_[_i][_j] = board1[_i][_j]\n",
    "\n",
    "        def near(i):\n",
    "            if i < 3:\n",
    "                return 0\n",
    "            if i < 6:\n",
    "                return 3\n",
    "            return 6\n",
    "\n",
    "        def square(i, j):\n",
    "            i, j = near(i), near(j)\n",
    "            ans = []\n",
    "            for a in range(i, i + 3):\n",
    "                for b in range(j, j + 3):\n",
    "                    ans.append(board[a][b])\n",
    "            return ans\n",
    "\n",
    "        def valid(arr):\n",
    "            temp = []\n",
    "            for x in arr:\n",
    "                if x not in temp:\n",
    "                    temp.append(x)\n",
    "                else:\n",
    "                    if x != '.':\n",
    "                        return False\n",
    "            return True\n",
    "\n",
    "        def valid_all(i, j):\n",
    "            pass\n",
    "\n",
    "        def permute(nums):\n",
    "            return list(permutations(nums, len(nums)))\n",
    "\n",
    "        def done():\n",
    "            for i in range(len(board)):\n",
    "                for j in range(len(board[0])):\n",
    "                    if board[i][j] == '.':\n",
    "                        return False\n",
    "            return True\n",
    "\n",
    "        def solve_one(row, column):\n",
    "            arr = ['1', '2', '3', '4', '5', '6', '7', '8', '9']\n",
    "            for i in range(9):\n",
    "                if board[row][i] in arr:\n",
    "                    arr.remove(board[row][i])\n",
    "            for i in range(9):\n",
    "                if board[i][column] in arr:\n",
    "                    arr.remove(board[i][column])\n",
    "            grid = square(row, column)\n",
    "            for i in range(9):\n",
    "                if grid[i] in arr:\n",
    "                    arr.remove(grid[i])\n",
    "            s = ''\n",
    "            for x in arr:\n",
    "                s += x\n",
    "            return s\n",
    "\n",
    "        def solve():\n",
    "            while True:\n",
    "                found = False\n",
    "                for i in range(len(board)):\n",
    "                    for j in range(len(board)):\n",
    "                        if board[i][j] == '.':\n",
    "                            elem = solve_one(i, j)\n",
    "                            if len(elem) == 1:\n",
    "                                board[i][j] = elem\n",
    "                                found = True\n",
    "                if not found:\n",
    "                    if done():\n",
    "                        return True\n",
    "                    break\n",
    "            return False\n",
    "\n",
    "        def permute_row(row):\n",
    "            arr = ['1', '2', '3', '4', '5', '6', '7', '8', '9']\n",
    "            filtered = []\n",
    "            arr2 = []\n",
    "            for i in range(9):\n",
    "                if board[row][i] in arr:\n",
    "                    arr.remove(board[row][i])\n",
    "            for i in range(9):\n",
    "                if board[row][i] == '.':\n",
    "                    elem = solve_one(row, i)\n",
    "                    arr2.append((elem, row, i))\n",
    "            perm = permute(arr)\n",
    "            for x in perm:\n",
    "                ok = True\n",
    "                for i in range(len(x)):\n",
    "                    try:\n",
    "                        arr2[i][0].index(x[i])\n",
    "                    except:\n",
    "                        ok = False\n",
    "                        break\n",
    "                if ok:\n",
    "                    filtered.append(x)\n",
    "            return filtered, arr2\n",
    "        ans = solve()\n",
    "        if ans:\n",
    "            return\n",
    "        bak = []\n",
    "        for i in range(9):\n",
    "            bak.append([0] * 9)\n",
    "        copy(board, bak)\n",
    "        for i in range(9):\n",
    "            ps, poss = permute_row(i)\n",
    "            j = 0\n",
    "            while j < len(ps):\n",
    "                p = ps[j]\n",
    "                copy(bak, board)\n",
    "                for k in range(len(p)):\n",
    "                    board[poss[k][1]][poss[k][2]] = p[k]\n",
    "                ans = solve()\n",
    "                if ans:\n",
    "                    return\n",
    "                else:\n",
    "                    j += 1\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class DLX:\n",
    "    \"\"\"\n",
    "    十字交叉双向循环链表\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(self, n):\n",
    "        \"\"\"\n",
    "        :param n: 数独的阶数\n",
    "        \"\"\"\n",
    "        self.n = n\n",
    "        self.m = n ** 2 * n ** 2 * 4 + 1  # 总共的列数(标注节点数+头节点)\n",
    "        self.max_nums = n ** 2 * n ** 2 * n ** 2 * 4 + self.m  # 最大节点编号\n",
    "\n",
    "        # 用下标表示节点编号，下标0表示节点0（即头节点），下标1表示节点1，以此类推...\n",
    "        self.u = [0 for _ in range(self.max_nums)]  # 记录节点的上链接点\n",
    "        self.d = [0 for _ in range(self.max_nums)]  # 记录节点的下链接点\n",
    "        self.l = [0 for _ in range(self.max_nums)]  # 记录节点的左链接点\n",
    "        self.r = [0 for _ in range(self.max_nums)]  # 记录节点的右链接点\n",
    "        self.row = [0 for _ in range(self.max_nums)]  # 记录节点所在的行\n",
    "        self.col = [0 for _ in range(self.max_nums)]  # 记录节点所在的列\n",
    "\n",
    "        # 设置首行的上下左右链接关系\n",
    "        for i in range(self.m):\n",
    "            self.u[i] = i\n",
    "            self.d[i] = i\n",
    "            self.r[i] = i + 1\n",
    "            self.l[i] = i - 1\n",
    "            self.row[i] = 0\n",
    "            self.col[i] = i\n",
    "        self.head = 0\n",
    "        self.l[self.head] = self.m - 1\n",
    "        self.r[self.m - 1] = self.head\n",
    "\n",
    "        self.s = [0 for _ in range(self.m)]  # 记录每列节点个数，以便搜索时选择节点数最少的列删除（即优化搜索方向）\n",
    "\n",
    "        self.next_point = self.m  # 下一个节点编号\n",
    "\n",
    "        self.ans = [0 for _ in range(n ** 2 * n ** 2 * n ** 2)]  # 所有答案的集合\n",
    "        self.end = 0\n",
    "\n",
    "    def add_row(self, row, columns):\n",
    "        \"\"\"\n",
    "        :param row: 新增节点所在的行\n",
    "        :param columns: 新增节点所在的列\n",
    "        :return:\n",
    "        \"\"\"\n",
    "        first = self.next_point\n",
    "        self.l[first] = first\n",
    "        self.r[first] = first\n",
    "\n",
    "        for c in columns:\n",
    "            # 先增加新节点对上下左右节点的指向\n",
    "            self.u[self.next_point] = self.u[c]\n",
    "            self.d[self.next_point] = c\n",
    "            self.l[self.next_point] = self.l[first]\n",
    "            self.r[self.next_point] = first\n",
    "            self.row[self.next_point] = row\n",
    "            self.col[self.next_point] = c\n",
    "\n",
    "            # 然后修改上下左右节点的指向，即指向新节点\n",
    "            self.r[self.l[first]] = self.next_point\n",
    "            self.l[first] = self.next_point\n",
    "            self.d[self.u[c]] = self.next_point\n",
    "            self.u[c] = self.next_point\n",
    "\n",
    "            self.s[c] += 1  # 该列节点数+1\n",
    "\n",
    "            self.next_point += 1  # 节点编号+1\n",
    "\n",
    "    def remove(self, c):\n",
    "        \"\"\"\n",
    "        删除第c列\n",
    "        :param c:\n",
    "        :return:\n",
    "        \"\"\"\n",
    "        self.l[self.r[c]] = self.l[c]\n",
    "        self.r[self.l[c]] = self.r[c]\n",
    "\n",
    "        i = self.d[c]\n",
    "        while i != c:\n",
    "            j = self.r[i]\n",
    "            while j != i:\n",
    "                self.d[self.u[j]] = self.d[j]\n",
    "                self.u[self.d[j]] = self.u[j]\n",
    "                self.s[self.col[j]] -= 1\n",
    "                j = self.r[j]\n",
    "            i = self.d[i]\n",
    "\n",
    "    def restore(self, c):\n",
    "        \"\"\"\n",
    "        恢复第c列\n",
    "        :param c:\n",
    "        :return:\n",
    "        \"\"\"\n",
    "        i = self.u[c]\n",
    "        while i != c:\n",
    "            j = self.l[i]\n",
    "            while j != i:\n",
    "                self.d[self.u[j]] = j\n",
    "                self.u[self.d[j]] = j\n",
    "                self.s[self.col[j]] += 1\n",
    "                j = self.l[j]\n",
    "            i = self.u[i]\n",
    "        self.l[self.r[c]] = c\n",
    "        self.r[self.l[c]] = c\n",
    "\n",
    "    def dance(self, step):\n",
    "        \"\"\"\n",
    "        :param step: 递归深度\n",
    "        :return:\n",
    "        \"\"\"\n",
    "        if self.r[self.head] == self.head:\n",
    "            self.end = step\n",
    "            return True\n",
    "\n",
    "        c = self.r[self.head]\n",
    "        j = self.r[self.head]\n",
    "        # 选择节点数最少的列\n",
    "        while j != self.head:\n",
    "            if self.s[j] < self.s[c]:\n",
    "                c = j\n",
    "            j = self.r[j]\n",
    "        self.remove(c)\n",
    "\n",
    "        i = self.d[c]\n",
    "        while i != c:\n",
    "            # 删除节点i所在的行，并将其保存到结果集中\n",
    "            self.ans[step] = self.row[i]\n",
    "            j = self.r[i]\n",
    "            while j != i:\n",
    "                self.remove(self.col[j])\n",
    "                j = self.r[j]\n",
    "            if self.dance(step + 1):  # 搜索成功则返回\n",
    "                return True\n",
    "\n",
    "            # 搜索失败，要恢复，回溯\n",
    "            self.ans[step] = 0\n",
    "            j = self.l[i]\n",
    "            while j != i:\n",
    "                self.restore(self.col[j])\n",
    "                j = self.l[j]\n",
    "\n",
    "            i = self.d[i]\n",
    "        self.restore(c)\n",
    "        return False\n",
    "\n",
    "    def transform_input(self, i, j, num):\n",
    "        c1 = self.n ** 2 * (i - 1) + j\n",
    "        c2 = self.n ** 2 * self.n ** 2 + self.n ** 2 * (i - 1) + num\n",
    "        c3 = self.n ** 2 * self.n ** 2 * 2 + self.n ** 2 * (j - 1) + num\n",
    "        c4 = self.n ** 2 * self.n ** 2 * 3 + self.n ** 2 * ((i - 1) // self.n * self.n + (j - 1) // self.n) + num\n",
    "        return c1, c2, c3, c4\n",
    "\n",
    "    def run(self, input_str):\n",
    "        input_matrix = []\n",
    "        row_index = 1\n",
    "        for i in range(1, self.n ** 2 + 1):\n",
    "            for j in range(1, self.n ** 2 + 1):\n",
    "                if input_str[i - 1][j - 1] != '.':\n",
    "                    tmp = int(input_str[i - 1][j - 1])\n",
    "                    input_matrix.append((i, j, tmp))\n",
    "                    self.add_row(row_index, self.transform_input(i, j, tmp))\n",
    "                    row_index += 1\n",
    "                else:\n",
    "                    for k in range(1, self.n ** 2 + 1):\n",
    "                        input_matrix.append((i, j, k))\n",
    "                        self.add_row(row_index, self.transform_input(i, j, k))\n",
    "                        row_index += 1\n",
    "\n",
    "        if self.dance(0):\n",
    "            for i in self.ans[:self.end]:\n",
    "                input_str[input_matrix[i - 1][0] - 1][input_matrix[i - 1][1] - 1] = str(input_matrix[i - 1][2])\n",
    "        else:\n",
    "            print('Impossible')\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        dlx = DLX(3)\n",
    "        dlx.run(board)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        self.backtracking(board)\n",
    "\n",
    "    def backtracking(self, board: List[List[str]]) -> bool:\n",
    "        # 若有解，返回True；若无解，返回False\n",
    "        for i in range(len(board)): # 遍历行\n",
    "            for j in range(len(board[0])):  # 遍历列\n",
    "                # 若空格内已有数字，跳过\n",
    "                if board[i][j] != '.': continue\n",
    "                for k in range(1, 10):  \n",
    "                    if self.is_valid(i, j, k, board):\n",
    "                        board[i][j] = str(k)\n",
    "                        if self.backtracking(board): return True\n",
    "                        board[i][j] = '.'\n",
    "                # 若数字1-9都不能成功填入空格，返回False无解\n",
    "                return False\n",
    "        return True # 有解\n",
    "\n",
    "    def is_valid(self, row: int, col: int, val: int, board: List[List[str]]) -> bool:\n",
    "        # 判断同一行是否冲突\n",
    "        for i in range(9):\n",
    "            if board[row][i] == str(val):\n",
    "                return False\n",
    "        # 判断同一列是否冲突\n",
    "        for j in range(9):\n",
    "            if board[j][col] == str(val):\n",
    "                return False\n",
    "        # 判断同一九宫格是否有冲突\n",
    "        start_row = (row // 3) * 3\n",
    "        start_col = (col // 3) * 3\n",
    "        for i in range(start_row, start_row + 3):\n",
    "            for j in range(start_col, start_col + 3):\n",
    "                if board[i][j] == str(val):\n",
    "                    return False\n",
    "        return True\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        status = self.backtracking(board)\n",
    "        # print('main:    ', board)\n",
    "    \n",
    "    def backtracking(self, board):\n",
    "        for row in range(9):\n",
    "            for col in range(9):\n",
    "                if board[row][col] != \".\":\n",
    "                    full_status = True\n",
    "                    continue\n",
    "                \n",
    "                ans_can = [str(i) for i in range(1,10)]\n",
    "                # search row\n",
    "                for j in range(9):\n",
    "                    if board[row][j] == \".\":\n",
    "                        continue\n",
    "                    if board[row][j] in ans_can:\n",
    "                        ans_can.remove(board[row][j])\n",
    "                # search col\n",
    "                for i in range(9):\n",
    "                    if board[i][col] == \".\":\n",
    "                        continue\n",
    "                    if board[i][col] in ans_can:\n",
    "                        ans_can.remove(board[i][col])\n",
    "                # search block\n",
    "                for i in range(3 * (row // 3), 3 * (row // 3)+3):\n",
    "                    for j in range(3 * (col // 3), 3 * (col // 3)+3):\n",
    "                        if board[i][j] == \".\":\n",
    "                            continue\n",
    "                        if board[i][j] in ans_can:\n",
    "                            ans_can.remove(board[i][j])\n",
    "                if not ans_can:\n",
    "                    return False\n",
    "                # print('can: ', row, col, ans_can)\n",
    "                for ans in ans_can:\n",
    "                    board[row][col] = ans\n",
    "                    # print('ans: ', row, col, ans)\n",
    "                    status = self.backtracking(board)\n",
    "                    if status:\n",
    "                        # print('board: ', board)\n",
    "                        return status\n",
    "                    board[row][col] = \".\"\n",
    "                if not status:\n",
    "                    return False\n",
    "        if full_status:\n",
    "            # print('full_status: ', board)\n",
    "            return True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "    \n",
    "        def isValid(i,j,num):\n",
    "            for tmp_i in range(9):\n",
    "                if board[tmp_i][j]==str(num):\n",
    "                    return False\n",
    "            for tmp_j in range(9):\n",
    "                if board[i][tmp_j]==str(num):\n",
    "                    return False\n",
    "            \n",
    "            for tmp_i in range(i//3*3, i//3*3+3):\n",
    "                for tmp_j in range(j//3*3, j//3*3+3):\n",
    "                    if board[tmp_i][tmp_j]==str(num):\n",
    "                        return False\n",
    "            return True\n",
    "\n",
    "        def backtrace():\n",
    "            for i in range(9):\n",
    "                for j in range(9):\n",
    "                    if board[i][j]=='.':\n",
    "                        for num in range(1,10):\n",
    "                            if isValid(i,j,num):\n",
    "                                board[i][j]=str(num)\n",
    "                                if backtrace():\n",
    "                                    return True\n",
    "                                board[i][j]='.'\n",
    "                        return False\n",
    "            return True\n",
    "\n",
    "        backtrace()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]):\n",
    "        def dfs(pos: int):\n",
    "            nonlocal valid\n",
    "            if pos == len(spaces):\n",
    "                valid = True\n",
    "                return\n",
    "\n",
    "            i, j = spaces[pos]\n",
    "            for digit in range(9):\n",
    "                if line[i][digit] == column[j][digit] == block[i // 3][j // 3][digit] == False:\n",
    "                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = True\n",
    "                    board[i][j] = str(digit + 1)\n",
    "                    dfs(pos + 1)\n",
    "                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = False\n",
    "                if valid:\n",
    "                    return\n",
    "\n",
    "        line = [[False] * 9 for _ in range(9)]\n",
    "        column = [[False] * 9 for _ in range(9)]\n",
    "        block = [[[False] * 9 for _a in range(3)] for _b in range(3)]\n",
    "        valid = False\n",
    "        spaces = list()\n",
    "\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if board[i][j] == \".\":\n",
    "                    spaces.append((i, j))\n",
    "                else:\n",
    "                    digit = int(board[i][j]) - 1\n",
    "                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = True\n",
    "\n",
    "        dfs(0)\n",
    "        return board"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "\n",
    "        def check(x, y, value):\n",
    "            if board[x][y] != '.':\n",
    "                return False\n",
    "            if value in [i for i in board[x]]:\n",
    "                return False\n",
    "            if value in [i[y] for i in board]:\n",
    "                return False\n",
    "            around_x_start = (x//3) * 3\n",
    "            around_x_end = around_x_start+3\n",
    "            around_y_start = (y//3) * 3\n",
    "            around_y_end = around_y_start+3\n",
    "            around_values = []\n",
    "            for x_ in range(around_x_start, around_x_end):\n",
    "                for y_ in range(around_y_start, around_y_end):\n",
    "                    around_values.append(board[x_][y_])\n",
    "            if value in around_values:\n",
    "                return False\n",
    "            return True\n",
    "\n",
    "        def back_tracking():\n",
    "            for x in range(0, 9):\n",
    "                for y in range(0, 9):\n",
    "                    if board[x][y] != '.':\n",
    "                        continue\n",
    "                    for value in range(1, 10):\n",
    "                        value = str(value)\n",
    "                        if check(x, y, value):\n",
    "                            board[x][y] = value\n",
    "                            state = back_tracking()\n",
    "                            if state:\n",
    "                                return True\n",
    "                            board[x][y] = '.'\n",
    "                    return False\n",
    "            return True\n",
    "\n",
    "        back_tracking()\n",
    "        return\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        lst = [(i, j) for i in range(9) for j in range(9) if board[i][j] == '.']\n",
    "        se  = set(\"123456789\")\n",
    "        n   = len(lst)\n",
    "        \n",
    "        def dfs(k):            \n",
    "            if k == n: return True   \n",
    "            i, j = lst[k]\n",
    "            ii, jj = i // 3 * 3, j // 3 * 3\n",
    "            for board[i][j] in set(\"123456789\") - set(board[i]) - set(list(zip(*board))[j]) - set(board[ii][jj : jj + 3] + board[ii + 1][jj : jj + 3] + board[ii + 2][jj : jj + 3]):\n",
    "                if dfs(k + 1): return True\n",
    "            board[i][j] = '.'             \n",
    "            return False                    \n",
    "        dfs(0)                            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        sudu = {str(i) for i in range(1, 10)}\n",
    "\n",
    "        def is_vaild(val, row, col):\n",
    "            # 判断同一行是否冲突\n",
    "            for i in range(9):\n",
    "                if board[row][i] == str(val):\n",
    "                    return False\n",
    "            # 判断同一列是否冲突\n",
    "            for j in range(9):\n",
    "                if board[j][col] == str(val):\n",
    "                    return False\n",
    "            # 判断同一九宫格是否有冲突\n",
    "            start_row = (row // 3) * 3\n",
    "            start_col = (col // 3) * 3\n",
    "            for i in range(start_row, start_row + 3):\n",
    "                for j in range(start_col, start_col + 3):\n",
    "                    if board[i][j] == str(val):\n",
    "                        return False\n",
    "            return True\n",
    "\n",
    "        def backtrack():\n",
    "            for row_inx in range(9):\n",
    "                for col_inx in range(9):\n",
    "                    if board[row_inx][col_inx] == \".\":\n",
    "                        for _su in sudu:\n",
    "                            if is_vaild(_su, row_inx, col_inx):\n",
    "                                board[row_inx][col_inx] = _su\n",
    "                                if backtrack():\n",
    "                                    return True\n",
    "                                board[row_inx][col_inx] = \".\"\n",
    "                        return False\n",
    "            return True\n",
    "\n",
    "        backtrack()\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        self.backtracking(board)\n",
    "\n",
    "    def backtracking(self, board: List[List[str]]) -> bool:\n",
    "        # 若有解，返回True；若无解，返回False\n",
    "        for i in range(len(board)): # 遍历行\n",
    "            for j in range(len(board[0])):  # 遍历列\n",
    "                # 若空格内已有数字，跳过\n",
    "                if board[i][j] != '.': continue\n",
    "                for k in range(1, 10):\n",
    "                    if self.is_valid(i, j, k, board):\n",
    "                        board[i][j] = str(k)\n",
    "                        if self.backtracking(board): return True\n",
    "                        board[i][j] = '.'\n",
    "                # 若数字1-9都不能成功填入空格，返回False无解\n",
    "                return False\n",
    "        return True # 有解\n",
    "\n",
    "    def is_valid(self, row: int, col: int, val: int, board: List[List[str]]) -> bool:\n",
    "        # 判断同一行是否冲突\n",
    "        for i in range(9):\n",
    "            if board[row][i] == str(val):\n",
    "                return False\n",
    "        # 判断同一列是否冲突\n",
    "        for j in range(9):\n",
    "            if board[j][col] == str(val):\n",
    "                return False\n",
    "        # 判断同一九宫格是否有冲突\n",
    "        start_row = (row // 3) * 3\n",
    "        start_col = (col // 3) * 3\n",
    "        for i in range(start_row, start_row + 3):\n",
    "            for j in range(start_col, start_col + 3):\n",
    "                if board[i][j] == str(val):\n",
    "                    return False\n",
    "        return True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        def isvalid(i, j, num):\n",
    "            if str(num) in board[i]:\n",
    "                return False\n",
    "            for x in range(0, len(board)):\n",
    "                if str(num) == board[x][j]:\n",
    "                    return False\n",
    "            for x in range(i//3*3, i//3*3+3):\n",
    "                for y in range(j//3*3, j//3*3+3):\n",
    "                    if board[x][y] == str(num):\n",
    "                        return False\n",
    "            return True\n",
    "\n",
    "        def backtrack():\n",
    "            for i in range(0, len(board)):\n",
    "                for j in range(0, len(board[0])):\n",
    "                    if board[i][j] == '.':\n",
    "                        for num in range(1, 10):\n",
    "                            if isvalid(i, j, num):\n",
    "                                board[i][j] = str(num)\n",
    "                                if backtrack(): return True\n",
    "                                board[i][j] = '.'\n",
    "                        return False\n",
    "            return True\n",
    "\n",
    "        backtrack()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        def dfs(pos: int):\n",
    "            nonlocal valid\n",
    "            if pos == len(spaces):\n",
    "                valid = True\n",
    "                return\n",
    "            \n",
    "            i, j = spaces[pos]\n",
    "            for digit in range(9):\n",
    "                if line[i][digit] == column[j][digit] == block[i // 3][j // 3][digit] == False:\n",
    "                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = True\n",
    "                    board[i][j] = str(digit + 1)\n",
    "                    dfs(pos + 1)\n",
    "                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = False\n",
    "                if valid:\n",
    "                    return\n",
    "            \n",
    "        line = [[False] * 9 for _ in range(9)]\n",
    "        column = [[False] * 9 for _ in range(9)]\n",
    "        block = [[[False] * 9 for _a in range(3)] for _b in range(3)]\n",
    "        valid = False\n",
    "        spaces = list()\n",
    "\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if board[i][j] == \".\":\n",
    "                    spaces.append((i, j))\n",
    "                else:\n",
    "                    digit = int(board[i][j]) - 1\n",
    "                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = True\n",
    "\n",
    "        dfs(0)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# class Solution:\n",
    "#     def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "#         \"\"\"\n",
    "#         Do not return anything, modify board in-place instead.\n",
    "#         \"\"\"\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        self.backtracking(board)\n",
    "\n",
    "    def backtracking(self, board: List[List[str]]) -> bool:\n",
    "        # 若有解，返回True；若无解，返回False\n",
    "        for i in range(9): # 遍历行\n",
    "            for j in range(9):  # 遍历列\n",
    "                # 若空格内已有数字，跳过\n",
    "                if board[i][j] != '.': continue\n",
    "                for k in range(1, 10):\n",
    "                    if self.is_valid(i, j, k, board):\n",
    "                        board[i][j] = str(k)\n",
    "                        if self.backtracking(board): return True\n",
    "                        board[i][j] = '.'\n",
    "                # 若数字1-9都不能成功填入空格，返回False无解\n",
    "                return False\n",
    "        return True # 有解\n",
    "\n",
    "    def is_valid(self, row: int, col: int, val: int, board: List[List[str]]) -> bool:\n",
    "        # 判断同一行是否冲突\n",
    "        for i in range(9):\n",
    "            if board[row][i] == str(val):\n",
    "                return False\n",
    "        # 判断同一列是否冲突\n",
    "        for j in range(9):\n",
    "            if board[j][col] == str(val):\n",
    "                return False\n",
    "        # 判断同一九宫格是否有冲突\n",
    "        start_row = (row // 3) * 3\n",
    "        start_col = (col // 3) * 3\n",
    "        for i in range(start_row, start_row + 3):\n",
    "            for j in range(start_col, start_col + 3):\n",
    "                if board[i][j] == str(val):\n",
    "                    return False\n",
    "        return True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "\n",
    "        def is_valid(row,col,num_str,board):\n",
    "            # same row\n",
    "            for i in range(len(board)):\n",
    "                if board[row][i]==num_str:\n",
    "                    return False\n",
    "            # same col\n",
    "            for i in range(len(board)):\n",
    "                if board[i][col]==num_str:\n",
    "                    return False\n",
    "            # 3*3\n",
    "            row_start = 3*(row//3)\n",
    "            col_start = 3*(col//3)\n",
    "            for i in range(row_start,row_start+3):\n",
    "                for j in range(col_start,col_start+3):\n",
    "                    if board[i][j]==num_str:\n",
    "                        return False\n",
    "            return True\n",
    "\n",
    "        def backtracking(board):\n",
    "            for i in range(len(board)):\n",
    "                for j in range(len(board)):\n",
    "                    if not board[i][j]==\".\":\n",
    "                        continue\n",
    "                    for k in range(1,10):\n",
    "                        k=str(k)\n",
    "                        if is_valid(i,j,k,board):\n",
    "                            board[i][j]=k\n",
    "                            if backtracking(board):\n",
    "                                return True\n",
    "                            board[i][j]=\".\"\n",
    "                    return False\n",
    "            return True\n",
    "        backtracking(board)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        lst, se = [(i, j) for i in range(9) for j in range(9) if board[i][j] == '.'], set(\"123456789\")\n",
    "        n = len(lst)\n",
    "        def dfs(k):            \n",
    "            if k == n: return True   \n",
    "            i, j = lst[k]\n",
    "            ii, jj = i // 3 * 3, j // 3 * 3\n",
    "            for board[i][j] in set(\"123456789\") - set(board[i]) - set(list(zip(*board))[j]) - set(board[ii][jj : jj + 3] + board[ii + 1][jj : jj + 3] + board[ii + 2][jj : jj + 3]):\n",
    "                if dfs(k + 1): return True\n",
    "            board[i][j] = '.'\n",
    "            return False  \n",
    "        dfs(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        self.backtracking(board)\n",
    "    def backtracking(self,board):\n",
    "        for i in range(len(board)):\n",
    "            for j in range(len(board[0])):\n",
    "                if board[i][j]!='.':\n",
    "                    continue\n",
    "                for k in range (1,10):\n",
    "                    if self.isValid(i,j,str(k),board):\n",
    "                        board[i][j]=str(k)\n",
    "                        if self.backtracking(board):\n",
    "                            return True\n",
    "                        board[i][j]='.'\n",
    "                return False    #1到9都没有无解\n",
    "        return True\n",
    "    def isValid(self,x,y,val,board):\n",
    "        ###按行查询\n",
    "        for i in range(len(board[0])):\n",
    "            if board[x][i]==val:\n",
    "                return False\n",
    "        ###按列查询\n",
    "        for i in range(len(board)):\n",
    "            if board[i][y]==val:\n",
    "                return False\n",
    "        ###按表格查询\n",
    "        start_row = (x//3)*3\n",
    "        start_col = (y//3)*3\n",
    "        for i in range(3):\n",
    "            for j in range(3):\n",
    "                if board[start_row+i][start_col+j]==val:\n",
    "                    return False\n",
    "        return True\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        self.dfs(board)\n",
    "    \n",
    "    def dfs(self, board) -> bool:\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if board[i][j] == '.':\n",
    "                    for k in range(1, 10):\n",
    "                        if self.isValid(i, j, k, board):\n",
    "                            board[i][j] = str(k)\n",
    "                            if self.dfs(board):\n",
    "                                return True\n",
    "                            board[i][j] = '.'\n",
    "                    return False\n",
    "        return True\n",
    "    \n",
    "    def isValid(self, row, col, k, board):\n",
    "        for j in range(9):\n",
    "            if board[row][j] == str(k):\n",
    "                return False\n",
    "        \n",
    "        for i in range(9):\n",
    "            if board[i][col] == str(k):\n",
    "                return False\n",
    "        \n",
    "        x = (row // 3) * 3\n",
    "        y = (col // 3) * 3\n",
    "        for i in range(x, x + 3):\n",
    "            for j in range(y, y + 3):\n",
    "                if board[i][j] == str(k):\n",
    "                    return False\n",
    "        \n",
    "        return True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        # try1【暴力回溯】\n",
    "        row = len(board)\n",
    "        col = len(board[0])\n",
    "        # 维护每行每列每格中1-9个数字是否能进行填写（0代表能进行填写）\n",
    "        row_number = [[[0] for i in range(9)] for j in range(row)]\n",
    "        col_number = [[[0] for i in range(9)] for j in range(col)]\n",
    "        block_number = [[[0] for i in range(9)] for j in range(9)]\n",
    "\n",
    "        # 判断第i行第j列的空格能不能填写第k个数字\n",
    "        def justice(i, j, k):\n",
    "            if row_number[i][k] == 1 or col_number[j][k] == 1 or block_number[3*int(i/3) + int(j/3)][k] == 1:\n",
    "                return False\n",
    "            return True\n",
    "\n",
    "        # 将存在的数字进行填入\n",
    "        for i in range(row):\n",
    "            for j in range(col):\n",
    "                # 不能进行填写的数字\n",
    "                if board[i][j] != \".\":\n",
    "                    row_number[i][int(board[i][j]) - 1] = 1\n",
    "                    col_number[j][int(board[i][j]) - 1] = 1\n",
    "                    block_number[3*int(i/3) + int(j/3)][int(board[i][j]) - 1] = 1\n",
    "\n",
    "        # 进行数字的暴力填写\n",
    "        def dfs(board):\n",
    "            for i in range(row):\n",
    "                for j in range(col):\n",
    "                    if board[i][j] == \".\":\n",
    "                        for k in range(9):  # 从1-9一一进行枚举\n",
    "                            if justice(i, j, k) == True:\n",
    "                                board[i][j] = str(k + 1)\n",
    "                                row_number[i][k] = 1\n",
    "                                col_number[j][k] = 1\n",
    "                                block_number[3 * int(i / 3) + int(j / 3)][k] = 1\n",
    "                                # 在剩下的未填写空格继续找解\n",
    "                                if (dfs(board)): return True\n",
    "                                # 找不到正确答案进行回溯\n",
    "                                board[i][j] = \".\"\n",
    "                                row_number[i][k] = 0\n",
    "                                col_number[j][k] = 0\n",
    "                                block_number[3 * int(i / 3) + int(j / 3)][k] = 0\n",
    "                        return False\n",
    "            return True\n",
    "\n",
    "        dfs(board)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        self.dfs(board, 0, 0, 9)\n",
    "        return board\n",
    "    def dfs(self, board, i, j, n):\n",
    "        if i == n:\n",
    "            return True\n",
    "        if j == n:\n",
    "            return self.dfs(board, i + 1, 0, n)\n",
    "        if board[i][j] != '.':\n",
    "            return self.dfs(board, i, j + 1, n)\n",
    "        for k in range(ord('1'), ord('9') + 1):\n",
    "            ch = chr(k)\n",
    "            if not self.isValid(board, i, j, ch):\n",
    "                continue\n",
    "            board[i][j] = ch\n",
    "            if self.dfs(board, i, j + 1, n):\n",
    "                return True\n",
    "            board[i][j] = '.'\n",
    "        return False\n",
    "    def isValid(self, board, i, j, ch):\n",
    "        for k in range(9):\n",
    "            if board[i][k] == ch or board[k][j] == ch:\n",
    "                return False\n",
    "        for v in range(i // 3 * 3, i // 3 * 3 + 3):\n",
    "            for w in range(j // 3 * 3, j // 3 * 3 + 3):\n",
    "                if board[v][w] == ch:\n",
    "                    return False\n",
    "        return True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        self.backTracking(board)\n",
    "\n",
    "    def backTracking(self, board):\n",
    "        row, col = len(board), len(board[0])\n",
    "        for i in range(row):\n",
    "            for j in range(col):\n",
    "                if board[i][j] != '.': continue\n",
    "                for k in range(1,10):\n",
    "                    if self.is_valid(i, j, k, board):\n",
    "                        board[i][j] = str(k)\n",
    "                        if self.backTracking(board): return True\n",
    "                        board[i][j] = '.'\n",
    "                return False\n",
    "        return True\n",
    "    \n",
    "    def is_valid(self, row, col, val, board):\n",
    "        for i in range(9):\n",
    "            if board[row][i] == str(val): return False\n",
    "        for j in range(9):\n",
    "            if board[j][col] == str(val): return False\n",
    "        start_row = (row // 3) * 3\n",
    "        start_col = (col // 3) * 3\n",
    "        for i in range(start_row, start_row+3):\n",
    "            for j in range(start_col, start_col+3):\n",
    "                if board[i][j] == str(val): return False\n",
    "        return True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Solves the Sudoku puzzle using backtracking algorithm.\n",
    "        The board is a 2D list data structure.\n",
    "        \"\"\"\n",
    "        def find_empty_location(arr, l):\n",
    "            for row in range(9):\n",
    "                for col in range(9):\n",
    "                    if arr[row][col] == \".\":\n",
    "                        l[0] = row\n",
    "                        l[1] = col\n",
    "                        return True\n",
    "            return False\n",
    "\n",
    "        def used_in_row(arr, row, num):\n",
    "            for i in range(9):\n",
    "                if arr[row][i] == num:\n",
    "                    return True\n",
    "            return False\n",
    "\n",
    "        def used_in_col(arr, col, num):\n",
    "            for i in range(9):\n",
    "                if arr[i][col] == num:\n",
    "                    return True\n",
    "            return False\n",
    "\n",
    "        def used_in_box(arr, row, col, num):\n",
    "            for i in range(3):\n",
    "                for j in range(3):\n",
    "                    if arr[i + row][j + col] == num:\n",
    "                        return True\n",
    "            return False\n",
    "\n",
    "        def is_safe(arr, row, col, num):\n",
    "            return not used_in_row(arr, row, num) and not used_in_col(arr, col, num) and not used_in_box(arr, row - row % 3, col - col % 3, num)\n",
    "\n",
    "        def solve(arr):\n",
    "            l = [0, 0]\n",
    "            \n",
    "            # If there is no unassigned location, we are done\n",
    "            if not find_empty_location(arr, l):\n",
    "                return True\n",
    "            \n",
    "            # Assigning list values to row and col that we got from the above function\n",
    "            row, col = l\n",
    "\n",
    "            # Consider digits 1 to 9\n",
    "            for num in map(str, range(1, 10)):\n",
    "                # If looks promising\n",
    "                if is_safe(arr, row, col, num):\n",
    "                    # Make tentative assignment\n",
    "                    arr[row][col] = num\n",
    "\n",
    "                    # Return, if success\n",
    "                    if solve(arr):\n",
    "                        return True\n",
    "\n",
    "                    # Failure, unmake & try again\n",
    "                    arr[row][col] = \".\"\n",
    "            \n",
    "            # This triggers backtracking\n",
    "            return False\n",
    "        solve(board)\n",
    "        \n",
    "    # Utilize the backtracking algorithm to solve the sudoku\n",
    "    # if solve(board):\n",
    "    #     return board\n",
    "    # else:\n",
    "    #     return \"No solution exists\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        self.backtracking(board)\n",
    "    def backtracking(self, board):\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                num = 1\n",
    "                if board[i][j] != '.':\n",
    "                    continue\n",
    "                for num in range(1, 10):\n",
    "                    if self.isvalid(i, j, num, board):\n",
    "                        board[i][j] = str(num)\n",
    "                        if self.backtracking(board):\n",
    "                            return True\n",
    "                        board[i][j] = '.'\n",
    "                return False\n",
    "        return True\n",
    "                    \n",
    "    def isvalid(self, row, col, val, board):\n",
    "        for i in range(9):\n",
    "            if board[i][col] == str(val):\n",
    "                return False\n",
    "\n",
    "            if board[row][i] == str(val):\n",
    "                return False\n",
    "\n",
    "        start_row = (row // 3) * 3\n",
    "        start_col = (col // 3) * 3\n",
    "        for i in range(start_row, start_row+3):\n",
    "            for j in range(start_col, start_col+3):\n",
    "                if board[i][j] == str(val):\n",
    "                    return False\n",
    "\n",
    "        return True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        self.backtracking(board)\n",
    "    \n",
    "    def backtracking(self,board):\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if board[i][j] != '.':\n",
    "                    continue\n",
    "                for k in range(1,10):\n",
    "                    if self.check_pos(i,j,k,board):\n",
    "                        board[i][j]=str(k)\n",
    "                        if self.backtracking(board):\n",
    "                            return True\n",
    "                        board[i][j]='.'\n",
    "                return False\n",
    "        return True\n",
    "    \n",
    "    def check_pos(self,row,col,val,board):\n",
    "        for i in range(9):\n",
    "            if board[row][i]==str(val):\n",
    "                return False\n",
    "\n",
    "        for i in range(9):\n",
    "            if board[i][col]==str(val):\n",
    "                return False\n",
    "\n",
    "        s_row=(row // 3)*3\n",
    "        s_col=(col // 3)*3\n",
    "        for i in range(s_row,s_row+3):\n",
    "            for j in range(s_col,s_col+3):\n",
    "                if board[i][j]==str(val):\n",
    "                    return False\n",
    "        \n",
    "        return True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        def dfs(pos: int):\n",
    "            nonlocal valid\n",
    "            if pos == len(spaces):\n",
    "                valid = True\n",
    "                return\n",
    "            \n",
    "            i, j = spaces[pos]\n",
    "            for digit in range(9):\n",
    "                if line[i][digit] == column[j][digit] == block[i // 3][j // 3][digit] == False:\n",
    "                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = True\n",
    "                    board[i][j] = str(digit + 1)\n",
    "                    dfs(pos + 1)\n",
    "                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = False\n",
    "                if valid:\n",
    "                    return\n",
    "            \n",
    "        line = [[False] * 9 for _ in range(9)]\n",
    "        column = [[False] * 9 for _ in range(9)]\n",
    "        block = [[[False] * 9 for _a in range(3)] for _b in range(3)]\n",
    "        valid = False\n",
    "        spaces = list()\n",
    "\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if board[i][j] == \".\":\n",
    "                    spaces.append((i, j))\n",
    "                else:\n",
    "                    digit = int(board[i][j]) - 1\n",
    "                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = True\n",
    "\n",
    "        dfs(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]):\n",
    "        def isValid(board, row, col, num):\n",
    "            # 判断行是否合法\n",
    "            for i in range(9):\n",
    "                if board[row][i] == num:\n",
    "                    return False\n",
    "            # 判断列是否合法\n",
    "            for i in range(9):\n",
    "                if board[i][col] == num:\n",
    "                    return False\n",
    "            # 判断3*3是否合法\n",
    "            r = row // 3 * 3\n",
    "            c = col // 3 * 3\n",
    "            for i in range(r, r + 3):\n",
    "                for j in range(c, c + 3):\n",
    "                    if board[i][j] == num:\n",
    "                        return False\n",
    "            return True\n",
    "        \n",
    "        def backtrack(board):\n",
    "            for i in range(9):\n",
    "                for j in range(9):\n",
    "                    if board[i][j] == '.':\n",
    "                        for num in '123456789':\n",
    "                            if isValid(board, i, j, num):\n",
    "                                board[i][j] = num\n",
    "                                if backtrack(board):\n",
    "                                    return True\n",
    "                                else:\n",
    "                                    board[i][j] = '.'  # 回溯，尝试下一个数字\n",
    "                        return False  # 所有数字都尝试完了，无解\n",
    "            return True  # 所有空格都填满了，解 Found\n",
    "        \n",
    "        backtrack(board)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        def flip(i, j, x):\n",
    "            s = 1 << x\n",
    "            rows[i] ^= s \n",
    "            cols[j] ^= s\n",
    "            boxes[i//3][j//3] ^= s \n",
    "        \n",
    "        def dfs(pos):\n",
    "            nonlocal valid\n",
    "            if pos == len(spaces):\n",
    "                valid = True\n",
    "                return\n",
    "            \n",
    "            i, j = spaces[pos]\n",
    "            for k in range(9):\n",
    "                s = 1 << k\n",
    "                if rows[i] & s == 0 and cols[j] & s == 0 and boxes[i//3][j//3] & s == 0:\n",
    "                    flip(i, j, k)\n",
    "                    board[i][j] = str(k + 1)\n",
    "                    dfs(pos + 1)\n",
    "                    flip(i, j, k)\n",
    "                if valid:\n",
    "                    return \n",
    "\n",
    "        rows = [0] * 9\n",
    "        cols = [0] * 9\n",
    "        boxes = [[0] * 3 for _ in range(3)]\n",
    "        spaces = []\n",
    "        valid = False\n",
    "        for i, row in enumerate(board):\n",
    "            for j, x in enumerate(row):\n",
    "                if x == '.':\n",
    "                    spaces.append((i, j))\n",
    "                else:\n",
    "                    flip(i, j ,int(x)-1)\n",
    "        \n",
    "        dfs(0)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        def is_valid(board: List[List[str]], row: int, col: int, val: str) -> bool:\n",
    "            for i in range(9):\n",
    "                if board[i][col] == val or board[row][i] == val:\n",
    "                    return False\n",
    "            start_row = (row // 3) * 3\n",
    "            start_col = (col // 3) * 3\n",
    "            for r in range(start_row, start_row+3):\n",
    "                for c in range(start_col, start_col+3):\n",
    "                    if board[r][c] == val:\n",
    "                        return False\n",
    "            return True\n",
    "\n",
    "        def backtracking(board: List[List[str]]) -> bool:   \n",
    "            for i in range(len(board)):\n",
    "                for j in range(len(board)):\n",
    "                    if board[i][j] != '.':\n",
    "                        continue\n",
    "                    for num in range(1, 10):\n",
    "                        if not is_valid(board, i, j, str(num)):\n",
    "                            continue\n",
    "                        board[i][j] = str(num)\n",
    "                        if backtracking(board):\n",
    "                            return True\n",
    "                        board[i][j] = '.'\n",
    "                    return False\n",
    "            return True\n",
    "        backtracking(board)\n",
    "        return board"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        def backtrack(board, i, j):\n",
    "            \"\"\"i, j代表遍历到的行、列索引\"\"\"\n",
    "            if j == 9:                  # 遍历完最后一列后，转去遍历下一行\n",
    "                return backtrack(board, i+1, 0)\n",
    "            if i == 9:                  # 遍历完最后一行后，结束\n",
    "                return True\n",
    "            if board[i][j] != '.':      # 非空位置不用管\n",
    "                return backtrack(board, i, j+1)\n",
    "            for n in range(1, 10):      # 遍历选择列表，此处的选择是，给空白处填 \"1\" - \"9\" 中之一\n",
    "                c = str(n)\n",
    "                if not self.check(board, i, j, c):     # 判断选择的字符是否满足要求（不与其他位置冲突）\n",
    "                    continue\n",
    "                board[i][j] = c                 # 做出选择\n",
    "                if backtrack(board, i, j+1):    # 递归调用，直接return是因为只需要一个可行解，而不需要所有可行解\n",
    "                    return True\n",
    "                board[i][j] = '.'               # 撤销选择\n",
    "        backtrack(board, 0, 0)\n",
    "\n",
    "    def check(self, board, row, col, c):\n",
    "        for i in range(9):\n",
    "            if board[row][i] == c:\n",
    "                return False\n",
    "            if board[i][col] == c:\n",
    "                return False\n",
    "            if board[(row//3)*3 + i // 3][(col//3)*3 + i % 3] == c:\n",
    "                return False\n",
    "        return True\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        def isValid(board, i, j , str1):\n",
    "            if str1 in board[i]:\n",
    "                return False\n",
    "            for k in range(9):\n",
    "                if board[k][j] == str1:                  \n",
    "                    return False\n",
    "            p,q = i//3, j //3\n",
    "            for m in range(3):\n",
    "                for n in range(3):\n",
    "                    if board[p*3 + m][q *3 + n] == str1:\n",
    "                        return False\n",
    "            return True\n",
    "\n",
    "        def backtrack(board,i, j):\n",
    "            if i == 8 and j == 9:\n",
    "                return True\n",
    "            if j == 9:\n",
    "                i += 1\n",
    "                j = 0\n",
    "            \n",
    "            if board[i][j] == \".\":\n",
    "                for k in range(1,10):\n",
    "                    if isValid(board,i,j,str(k)):\n",
    "                        board[i][j] = str(k)\n",
    "                        if backtrack(board,i,j+1):\n",
    "                            return True\n",
    "                        else:\n",
    "                            board[i][j] = \".\"\n",
    "            else:\n",
    "                return backtrack(board,i,j+1)\n",
    "        \n",
    "        backtrack(board,0,0)\n",
    "        return board"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        row = [[False] * 9 for _ in range(9)]\n",
    "        col = [[False] * 9 for _ in range(9)]\n",
    "        cell = [[[False] * 9 for _ in range(3)] for _ in range(3)]\n",
    "\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if board[i][j] == \".\":\n",
    "                    continue\n",
    "                t = int(board[i][j]) - 1\n",
    "                row[i][t] = col[j][t] = cell[i // 3][j // 3][t] = True\n",
    "\n",
    "        def dfs(board: List[List[str]], x: int, y: int) -> None:\n",
    "            if y == 9: x, y = x + 1, 0\n",
    "            if x == 9: return True\n",
    "\n",
    "            if board[x][y] != \".\":\n",
    "                return dfs(board, x, y + 1)\n",
    "            \n",
    "            for i in range(9):\n",
    "                if row[x][i] or col[y][i] or cell[x // 3][y // 3][i]:\n",
    "                    continue\n",
    "                board[x][y] = str(i + 1)\n",
    "                row[x][i] = col[y][i] = cell[x // 3][y // 3][i] = True\n",
    "                if dfs(board, x, y + 1):\n",
    "                    return True\n",
    "                board[x][y] = \".\"\n",
    "                row[x][i] = col[y][i] = cell[x // 3][y // 3][i] = False\n",
    "\n",
    "        dfs(board, 0, 0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]):\n",
    "        def is_valid(board, row, col, num):\n",
    "            for i in range(9):\n",
    "                if board[row][i] == num:\n",
    "                    return False\n",
    "                if board[i][col] == num:\n",
    "                    return False\n",
    "                if board[(row//3)*3 + i//3][(col//3)*3 + i%3] == num:\n",
    "                    return False\n",
    "            return True\n",
    "        \n",
    "        def backtrack(board):\n",
    "            for i in range(9):\n",
    "                for j in range(9):\n",
    "                    if board[i][j] == '.':\n",
    "                        for num in range(1, 10):\n",
    "                            if is_valid(board, i, j, str(num)):\n",
    "                                board[i][j] = str(num)\n",
    "                                if backtrack(board):\n",
    "                                    return True\n",
    "                                board[i][j] = '.'\n",
    "                        return False\n",
    "            return True\n",
    "        \n",
    "        backtrack(board)\n",
    "        return board"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        def isValid(board, row, col, num):\n",
    "            for i in range(9):\n",
    "                if board[row][i] == num or board[i][col] == num or board[3 * (row // 3) + i // 3][3 * (col // 3) + i % 3] == num:\n",
    "                    return False\n",
    "            return True\n",
    "\n",
    "        def solve(board):\n",
    "            for i in range(9):\n",
    "                for j in range(9):\n",
    "                    if board[i][j] == '.':\n",
    "                        for num in map(str, range(1, 10)):\n",
    "                            if isValid(board, i, j, num):\n",
    "                                board[i][j] = num\n",
    "                                if solve(board):\n",
    "                                    return True\n",
    "                                board[i][j] = '.'\n",
    "                        return False\n",
    "            return True\n",
    "\n",
    "        solve(board)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        def dfs(pos):\n",
    "            nonlocal valid\n",
    "            if pos == len(spaces):\n",
    "                valid = True\n",
    "                return\n",
    "\n",
    "            i, j = spaces[pos]\n",
    "            for digit in range(9):\n",
    "                if line[i][digit] == column[j][digit] == block[i // 3][j // 3][digit] == False:\n",
    "                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = True\n",
    "                    board[i][j] = str(digit + 1)\n",
    "                    dfs(pos + 1)\n",
    "                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = False\n",
    "                if valid:\n",
    "                    return\n",
    "            \n",
    "        line = [[False] * 9 for _ in range(9)]\n",
    "        column = [[False] * 9 for _ in range(9)]\n",
    "        block = [[[False] * 9 for _a in range(3)] for _b in range(3)]\n",
    "        valid = False\n",
    "        spaces = list()\n",
    "\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if board[i][j] == \".\":\n",
    "                    spaces.append((i, j))\n",
    "                else:\n",
    "                    digit = int(board[i][j]) - 1\n",
    "                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = True\n",
    "\n",
    "        dfs(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        row = [[False]*9 for _ in range(9)]\n",
    "        col =[[False]*9 for _ in range(9)]\n",
    "        block =[[[False]*9 for _a in range(3)] for _b in range(3)]\n",
    "        space = []\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if board[i][j] != \".\":\n",
    "                    index = int(board[i][j])-1\n",
    "                    row[i][index] = True\n",
    "                    col[j][index] = True\n",
    "                    block[int(i/3)][int(j/3)][index] = True\n",
    "                else:\n",
    "                    space.append((i,j))\n",
    "        valid = False\n",
    "\n",
    "        def dfs(i):\n",
    "            nonlocal valid\n",
    "            if i == len(space):\n",
    "                valid = True\n",
    "                return\n",
    "            x,y = space[i]\n",
    "            for index in range(9):\n",
    "                if row[x][index] == col[y][index] == block[x//3][y//3][index] ==False:\n",
    "                    row[x][index]=col[y][index]=block[x//3][y//3][index]=True\n",
    "                    board[x][y] = str(index+1)\n",
    "                    dfs(i+1)\n",
    "                    row[x][index]=col[y][index]=block[x//3][y//3][index]=False\n",
    "                    if valid:\n",
    "                        return\n",
    "        dfs(0)\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "\n",
    "        def is_valid(board, row, col, num):\n",
    "            # 检查同一行是否合法\n",
    "            for i in range(9):\n",
    "                if board[row][i] == num:\n",
    "                    return False\n",
    "\n",
    "            # 检查同一列是否合法\n",
    "            for i in range(9):\n",
    "                if board[i][col] == num:\n",
    "                    return False\n",
    "\n",
    "            # 检查同一 3x3 宫内是否合法\n",
    "            start_row, start_col = 3 * (row // 3), 3 * (col // 3)\n",
    "            for i in range(3):\n",
    "                for j in range(3):\n",
    "                    if board[start_row + i][start_col + j] == num:\n",
    "                        return False\n",
    "\n",
    "            return True\n",
    "\n",
    "        def solve_sudoku(board):\n",
    "            for i in range(9):\n",
    "                for j in range(9):\n",
    "                    if board[i][j] == '.':\n",
    "                        for num in map(str, range(1, 10)):\n",
    "                            if is_valid(board, i, j, num):\n",
    "                                board[i][j] = num\n",
    "                                if solve_sudoku(board):\n",
    "                                    return True\n",
    "                                board[i][j] = '.'  # 回溯\n",
    "                        return False\n",
    "            return True\n",
    "\n",
    "        solve_sudoku(board)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "import copy\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        self.backtracking(board,0,0)\n",
    "    def backtracking(self,board,i,j):\n",
    "        n=len(board)\n",
    "        if i>=n:\n",
    "            return True\n",
    "        m=len(board[0])\n",
    "        if board[i][j]=='.':\n",
    "            for num in range(1,10):\n",
    "                if self.check_valid(board,i,j,num):\n",
    "                    board[i][j]=str(num)\n",
    "                    if j<m-1:\n",
    "                        if self.backtracking(board,i,j+1):\n",
    "                            return True\n",
    "                    if j==m-1:\n",
    "                        if self.backtracking(board,i+1,0):\n",
    "                            return True\n",
    "                    board[i][j]='.'\n",
    "            return False\n",
    "        else:\n",
    "            if j<m-1:\n",
    "                if self.backtracking(board,i,j+1):\n",
    "                    return True\n",
    "            if j==m-1:\n",
    "                if self.backtracking(board,i+1,0):\n",
    "                    return True\n",
    "            return False\n",
    "            \n",
    "    def check_valid(self,board,i,j,number):\n",
    "        for c in range(9):  #检查列\n",
    "            if board[c][j]==str(number):\n",
    "                return False\n",
    "        for l in range(9):  #检查行\n",
    "            if board[i][l]==str(number):\n",
    "                return False\n",
    "        c=(i//3)*3\n",
    "        l=(j//3)*3\n",
    "        for x in range(c,c+3):  #检查九宫格\n",
    "            for y in range(l,l+3):\n",
    "                if board[x][y]==str(number):\n",
    "                    return False\n",
    "        return True \n",
    "        \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        def dfs(pos: int):\n",
    "            nonlocal valid\n",
    "            if pos == len(spaces):\n",
    "                valid = True\n",
    "                return\n",
    "            \n",
    "            i, j = spaces[pos]\n",
    "            for digit in range(9):\n",
    "                if line[i][digit] == column[j][digit] == block[i // 3][j // 3][digit] == False:\n",
    "                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = True\n",
    "                    board[i][j] = str(digit + 1)\n",
    "                    dfs(pos + 1)\n",
    "                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = False\n",
    "                if valid:\n",
    "                    return\n",
    "            \n",
    "        line = [[False] * 9 for _ in range(9)]\n",
    "        column = [[False] * 9 for _ in range(9)]\n",
    "        block = [[[False] * 9 for _a in range(3)] for _b in range(3)]\n",
    "        valid = False\n",
    "        spaces = list()\n",
    "\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if board[i][j] == \".\":\n",
    "                    spaces.append((i, j))\n",
    "                else:\n",
    "                    digit = int(board[i][j]) - 1\n",
    "                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = True\n",
    "\n",
    "        dfs(0)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        self.backtracking(board)\n",
    "\n",
    "    def backtracking(self, board: List[List[str]]) -> bool:\n",
    "        # 若有解，返回True；若无解，返回False\n",
    "        for i in range(len(board)): # 遍历行\n",
    "            for j in range(len(board[0])):  # 遍历列\n",
    "                # 若空格内已有数字，跳过\n",
    "                if board[i][j] != '.': continue\n",
    "                for k in range(1, 10):\n",
    "                    if self.is_valid(i, j, k, board):\n",
    "                        board[i][j] = str(k)\n",
    "                        if self.backtracking(board): return True\n",
    "                        board[i][j] = '.'\n",
    "                # 若数字1-9都不能成功填入空格，返回False无解\n",
    "                return False\n",
    "        return True # 有解\n",
    "\n",
    "    def is_valid(self, row: int, col: int, val: int, board: List[List[str]]) -> bool:\n",
    "        # 判断同一行是否冲突\n",
    "        for i in range(9):\n",
    "            if board[row][i] == str(val):\n",
    "                return False\n",
    "        # 判断同一列是否冲突\n",
    "        for j in range(9):\n",
    "            if board[j][col] == str(val):\n",
    "                return False\n",
    "        # 判断同一九宫格是否有冲突\n",
    "        start_row = (row // 3) * 3\n",
    "        start_col = (col // 3) * 3\n",
    "        for i in range(start_row, start_row + 3):\n",
    "            for j in range(start_col, start_col + 3):\n",
    "                if board[i][j] == str(val):\n",
    "                    return False\n",
    "        return True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        self.n = len(board)\n",
    "        self.board = board\n",
    "        self.cols = [0] * self.n\n",
    "        self.rows = [0] * self.n\n",
    "        self.block = [[0 for i in range(self.n//3)] for j in range(self.n//3)]\n",
    "        self.get_bitset()\n",
    "        self.dfs()\n",
    "    \n",
    "    def get_bitset(self):\n",
    "        for i in range(self.n):\n",
    "            for j in range(self.n):\n",
    "                val = self.board[i][j]\n",
    "                if val == '.':\n",
    "                    continue\n",
    "                val_ord = ord(val) - ord('0') - 1\n",
    "                self.cols[j] += 1 << val_ord\n",
    "                self.rows[i] += 1 << val_ord\n",
    "                self.block[i//3][j//3] += 1 << val_ord\n",
    "    \n",
    "    def get_possible_status(self, row, col):\n",
    "        bit = ~(self.cols[col] | self.rows[row] | self.block[row//3][col//3])\n",
    "        return bit\n",
    "    \n",
    "    def get_next(self):\n",
    "        c_min = 10\n",
    "        c_pos = None\n",
    "        \n",
    "        for i in range(self.n):\n",
    "            for j in range(self.n):\n",
    "                c = 0\n",
    "                if self.board[i][j] == \".\":\n",
    "                    num = self.get_possible_status(i, j)\n",
    "                    for k in range(self.n):\n",
    "                        if num >> k & 1 == 1:\n",
    "                            c += 1\n",
    "                    if c < c_min:\n",
    "                        c_min = c\n",
    "                        c_pos = (i, j)\n",
    "        return c_pos\n",
    "    \n",
    "    def dfs(self):\n",
    "        next = self.get_next()\n",
    "        if next is None:\n",
    "            return True\n",
    "        (row, col) = next\n",
    "        bit_num = self.get_possible_status(row, col)\n",
    "            \n",
    "        for i in range(self.n):\n",
    "            if bit_num >> i & 1== 1:\n",
    "                self.board[row][col] = str(i+1)\n",
    "                self.fill_num(row, col, str(i+1), 'add')\n",
    "                if self.dfs():\n",
    "                    return True\n",
    "                self.fill_num(row, col, str(i+1), 'delete')\n",
    "                self.board[row][col] = '.'\n",
    "        return False\n",
    "                    \n",
    "    \n",
    "    def fill_num(self, row, col, num, opt):\n",
    "        val = self.board[row][col]\n",
    "        val_ord = ord(val) - ord('0') - 1\n",
    "        if opt == \"add\":\n",
    "            self.cols[col] += 1 << val_ord\n",
    "            self.rows[row] += 1 << val_ord\n",
    "            self.block[row//3][col//3] += 1 << val_ord\n",
    "        else:\n",
    "            self.cols[col] -= 1 << val_ord\n",
    "            self.rows[row] -= 1 << val_ord\n",
    "            self.block[row//3][col//3] -= 1 << val_ord\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def is_valid(self, row: int, col: int, val: int, board):\n",
    "        # 判断同一行是否冲突\n",
    "        for i in range(9):\n",
    "            if board[row][i] == str(val):\n",
    "                return False\n",
    "        # 判断同一列是否冲突\n",
    "        for j in range(9):\n",
    "            if board[j][col] == str(val):\n",
    "                return False\n",
    "        # 判断同一九宫格是否有冲突\n",
    "        start_row = (row // 3) * 3\n",
    "        start_col = (col // 3) * 3\n",
    "        for i in range(start_row, start_row + 3):\n",
    "            for j in range(start_col, start_col + 3):\n",
    "                if board[i][j] == str(val):\n",
    "                    return False\n",
    "        return True\n",
    "\n",
    "    def solveSudoku(self, board):\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "\n",
    "        def back(state):\n",
    "            for row in range(len(board)):\n",
    "                for col in range(len(board[0])):\n",
    "                    if board[row][col] != '.':\n",
    "                        continue\n",
    "                    for k in range(1, 10):\n",
    "                        if self.is_valid(row, col, k, state):\n",
    "                            state[row][col] = str(k)\n",
    "                            if back(state):\n",
    "                                return True\n",
    "                            state[row][col] = \".\"\n",
    "                    return False\n",
    "            return True\n",
    "        back(board)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        columns = [[0 for _ in range(9)] for _ in range(9)]\n",
    "        rows = [[0 for _ in range(9)] for _ in range(9)]\n",
    "        grids = [[[0 for _ in range(9)] for _ in range(3)] for _ in range(3)]\n",
    "\n",
    "\n",
    "        sublist = []\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if board[i][j] == '.':\n",
    "                    sublist.append((i,j))\n",
    "                else:\n",
    "                    num = int(board[i][j]) -1 \n",
    "                    columns[i][num] += 1 \n",
    "                    rows[j][num] += 1 \n",
    "                    grids[i//3][j//3][num] += 1 \n",
    "        valid = False\n",
    "        def dfs(path,idx):\n",
    "            nonlocal valid\n",
    "            if idx == len(path):\n",
    "                valid = True \n",
    "                return \n",
    "            i,j = path[idx]\n",
    "            for k in range(9):\n",
    "                if columns[i][k]==0 and rows[j][k] == 0 and grids[i//3][j//3][k] == 0:\n",
    "                    board[i][j] = str(k+1)\n",
    "                    columns[i][k] += 1 \n",
    "                    rows[j][k] += 1 \n",
    "                    grids[i//3][j//3][k] += 1 \n",
    "                    dfs(path,idx+1)\n",
    "              \n",
    "                    columns[i][k] -= 1 \n",
    "                    rows[j][k] -= 1 \n",
    "                    grids[i//3][j//3][k] -= 1 \n",
    "                \n",
    "                if valid:\n",
    "                    break\n",
    "        dfs(sublist,0)\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        self.back(board)\n",
    "        return board\n",
    "\n",
    "    def back(self, board):\n",
    "        # 若有解，返回True；若无解，返回False\n",
    "        for i in range(len(board)): # 遍历行\n",
    "            for j in range(len(board[0])):  # 遍历列\n",
    "                # 若空格内已有数字，跳过\n",
    "                if board[i][j] != '.': continue\n",
    "                for k in range(1, 10):\n",
    "                    if self.islegitimate(board, i, j, str(k)):\n",
    "                        board[i][j] = str(k)\n",
    "                        if self.back(board): return True\n",
    "                        board[i][j] = '.'\n",
    "                # 若数字1-9都不能成功填入空格，返回False无解\n",
    "                return False\n",
    "        return True # 有解\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "    def islegitimate(self, board, y, x, value):\n",
    "\n",
    "        for i in range(9):\n",
    "            if board[y][i] == value or board[i][x] == value:\n",
    "                return False\n",
    "\n",
    "        start_x = (x // 3) * 3\n",
    "        start_y = (y // 3) * 3\n",
    "        for i in range(start_x, start_x + 3):\n",
    "            for j in range(start_y, start_y + 3):\n",
    "                if board[j][i] == value:\n",
    "                    return False\n",
    "\n",
    "        return True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "import copy\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        self.backtracking(board,0,0)\n",
    "    def backtracking(self,board,i,j):\n",
    "        n=len(board)\n",
    "        if i>=n:\n",
    "            return True\n",
    "        m=len(board[0])\n",
    "        if board[i][j]=='.':\n",
    "            for num in range(1,10):\n",
    "                if self.check_valid(board,i,j,num):\n",
    "                    board[i][j]=str(num)\n",
    "                    if j<m-1:\n",
    "                        if self.backtracking(board,i,j+1):\n",
    "                            return True\n",
    "                    if j==m-1:\n",
    "                        if self.backtracking(board,i+1,0):\n",
    "                            return True\n",
    "                    board[i][j]='.'\n",
    "            return False\n",
    "        else:\n",
    "            if j<m-1:\n",
    "                if self.backtracking(board,i,j+1):\n",
    "                    return True\n",
    "            if j==m-1:\n",
    "                if self.backtracking(board,i+1,0):\n",
    "                    return True\n",
    "            return False\n",
    "            \n",
    "    def check_valid(self,board,i,j,number):\n",
    "        for c in range(9):  #检查列\n",
    "            if board[c][j]==str(number):\n",
    "                return False\n",
    "        for l in range(9):  #检查行\n",
    "            if board[i][l]==str(number):\n",
    "                return False\n",
    "        c=(i//3)*3\n",
    "        l=(j//3)*3\n",
    "        for x in range(c,c+3):  #检查九宫格\n",
    "            for y in range(l,l+3):\n",
    "                if board[x][y]==str(number):\n",
    "                    return False\n",
    "        return True \n",
    "        \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        # 判断是否在行、列、小方格出现\n",
    "        row = [[False] * 9 for _ in range(9)]\n",
    "        col = [[False] * 9 for _ in range(9)]\n",
    "        cell = [[[False] * 9 for _ in range(3)] for _ in range(3)]\n",
    "\n",
    "        # 预处理\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if board[i][j] != '.':\n",
    "                    t = ord(board[i][j]) - ord('1')\n",
    "                    row[i][t] = True\n",
    "                    col[j][t] = True\n",
    "                    cell[i // 3][j // 3][t] = True\n",
    "        def dfs(board, x, y):\n",
    "            # 列走到末尾则换行\n",
    "            if y == 9:\n",
    "                y = 0\n",
    "                x += 1\n",
    "            if x == 9:\n",
    "                return True\n",
    "            \n",
    "            # 不需要填数字\n",
    "            if board[x][y] != '.':\n",
    "                return dfs(board, x, y + 1)\n",
    "            \n",
    "            # 枚举(x,y)要填的数字\n",
    "            for t in range(1, 10):\n",
    "                if not row[x][t - 1] and not col[y][t - 1] and not cell[x // 3][y // 3][t - 1]:\n",
    "                    board[x][y] = str(t)\n",
    "                    row[x][t - 1] = True\n",
    "                    col[y][t - 1] = True\n",
    "                    cell[x // 3][y // 3][t - 1] = True\n",
    "\n",
    "                    if dfs(board, x, y + 1):\n",
    "                        return True\n",
    "                    \n",
    "                    # 恢复现场\n",
    "                    board[x][y] = '.'\n",
    "                    row[x][t - 1] = False\n",
    "                    col[y][t - 1] = False\n",
    "                    cell[x // 3][y // 3][t - 1] = False\n",
    "            \n",
    "            # 1 ~ 9都填不了\n",
    "            return False\n",
    "        \n",
    "        dfs(board, 0, 0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        nums = {'1', '2', '3', '4', '5', '6', '7', '8', '9'}\n",
    "        row = [set() for _ in range(9)]\n",
    "        column = [set() for _ in range(9)]\n",
    "        table = [[set() for _ in range(3)] for _ in range(3)]\n",
    "        empty = []\n",
    "\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                num = board[i][j]\n",
    "                if num == \".\":\n",
    "                    empty.append((i, j))\n",
    "                else:\n",
    "                    row[i].add(num)\n",
    "                    column[j].add(num)\n",
    "                    table[i//3][j//3].add(num)\n",
    "\n",
    "        def dfs(n):\n",
    "            if n == len(empty): return True\n",
    "            i, j = empty[n]\n",
    "            choice = nums - row[i] - column[j] - table[i//3][j//3]\n",
    "            for num in choice:\n",
    "                \n",
    "                row[i].add(num)\n",
    "                column[j].add(num)\n",
    "                table[i//3][j//3].add(num)\n",
    "                if dfs(n + 1): \n",
    "                    board[i][j] = num\n",
    "                    return True\n",
    "                row[i].remove(num)\n",
    "                column[j].remove(num)\n",
    "                table[i//3][j//3].remove(num)\n",
    "\n",
    "        dfs(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        self.backtracking(board)\n",
    "    \n",
    "\n",
    "    def backtracking(self,board:List[List[str]]) -> bool:\n",
    "        # 如果有解，返回True;如果没有解，返回False\n",
    "        for i in range(len(board)): # 遍历行\n",
    "            for j in range(len(board[0])): # 遍历列\n",
    "                # 若空格内已有数字，跳过\n",
    "                if board[i][j] != '.':continue\n",
    "                for k in range(1,10):\n",
    "                    if self.isValid(i,j,k,board):\n",
    "                        board[i][j] = str(k)\n",
    "                        if self.backtracking(board): return True\n",
    "                        board[i][j] = '.'\n",
    "                # 若1到9都不能成功填入空格，返回False无解\n",
    "                return False\n",
    "        return True # 上面都执行完了，没有遇到False的情况，证明有解\n",
    "    \n",
    "\n",
    "    def isValid(self,row:int,col:int,val:int,board:List[List[str]]) -> bool:\n",
    "        # 判断同一行是否冲突\n",
    "        for i in range(9):\n",
    "            if board[row][i] == str(val):\n",
    "                return False\n",
    "            # 判断同一列是否冲突\n",
    "        for j in range(9):\n",
    "            if board[j][col] == str(val):\n",
    "                return False\n",
    "        # 判断同一九宫格是否冲突：\n",
    "        start_row = (row//3) *3\n",
    "        start_col = (col//3) *3\n",
    "        for i in range(start_row,start_row+3):\n",
    "            for j in range(start_col,start_col+3):\n",
    "                if board[i][j] == str(val):\n",
    "                    return False\n",
    "            \n",
    "        return True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, grid: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "\n",
    "        board = copy.deepcopy(grid)\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if board[i][j] == \".\":\n",
    "                    board[i][j] = 0\n",
    "                else:\n",
    "                    board[i][j] = int(board[i][j])\n",
    "\n",
    "        def find_empty(board : List[List[str]]):\n",
    "            for i in range(9):\n",
    "                for j in range(9):\n",
    "                    if board[i][j] == 0:\n",
    "                        return (i,j)\n",
    "\n",
    "            return None\n",
    "\n",
    "        # is_valid() 判断 (row,col) 的格子中填 num 满不满足条件\n",
    "        def is_valid(num, row, col):\n",
    "            for i in range(9):\n",
    "                if board[row][i] == num or board[i][col] == num:\n",
    "                    return False\n",
    "            start_row, start_col = 3 * (row // 3), 3 * (col // 3)\n",
    "            for i in range(start_row, start_row + 3):\n",
    "                for j in range(start_col, start_col + 3):\n",
    "                    if board[i][j] == num:\n",
    "                        return False\n",
    "            return True\n",
    "\n",
    "\n",
    "        def dfs() -> bool:\n",
    "            p = find_empty(board)\n",
    "            i,j = -1,-1\n",
    "            if p != None:\n",
    "                i,j = p\n",
    "            else:\n",
    "                return True\n",
    "\n",
    "            # print(p)\n",
    "\n",
    "            for x in range(1,10):\n",
    "                # board[i][j] = x\n",
    "                # print(i,j,x)\n",
    "\n",
    "                if is_valid(x,i,j):\n",
    "                    board[i][j] = x\n",
    "\n",
    "                    if dfs():\n",
    "                        return True\n",
    "                    else:\n",
    "                        board[i][j] = 0\n",
    "                    \n",
    "\n",
    "            return False\n",
    "                    \n",
    "        \n",
    "        dfs()\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if grid[i][j] == '.':\n",
    "                    grid[i][j] = str(board[i][j])\n",
    "\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        def dfs(pos: int):\n",
    "            nonlocal valid\n",
    "            if pos == len(spaces):\n",
    "                valid = True\n",
    "                return\n",
    "            \n",
    "            i, j = spaces[pos]\n",
    "            for digit in range(9):\n",
    "                if line[i][digit] == column[j][digit] == block[i // 3][j // 3][digit] == False:\n",
    "                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = True\n",
    "                    board[i][j] = str(digit + 1)\n",
    "                    dfs(pos + 1)\n",
    "                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = False\n",
    "                if valid:\n",
    "                    return\n",
    "            \n",
    "        line = [[False] * 9 for _ in range(9)]\n",
    "        column = [[False] * 9 for _ in range(9)]\n",
    "        block = [[[False] * 9 for _a in range(3)] for _b in range(3)]\n",
    "        valid = False\n",
    "        spaces = list()\n",
    "\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if board[i][j] == \".\":\n",
    "                    spaces.append((i, j))\n",
    "                else:\n",
    "                    digit = int(board[i][j]) - 1\n",
    "                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = True\n",
    "\n",
    "        dfs(0)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        row = [[0]*9 for _ in range(9)]\n",
    "        col = [[0]*9 for _ in range(9)]\n",
    "        box = [[0]*9 for _ in range(9)]\n",
    "\n",
    "        def is_valid(i, j, num):\n",
    "            if row[i][num] == 1:\n",
    "                return False\n",
    "            if col[j][num] == 1:\n",
    "                return False\n",
    "            idx = i//3*3+j//3\n",
    "            if box[idx][num] == 1:\n",
    "                return False\n",
    "            return True\n",
    "\n",
    "        space = []\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if board[i][j] != \".\":\n",
    "                    num = int(board[i][j])-1\n",
    "                    row[i][num] = 1\n",
    "                    col[j][num] = 1\n",
    "                    box[i // 3 * 3 + j // 3][num] = 1\n",
    "                else:\n",
    "                    space.append([i,j])\n",
    "\n",
    "        def backtrack(index):\n",
    "            if index == len(space):\n",
    "                return True\n",
    "            i ,j = space[index]\n",
    "            for n in range(9):\n",
    "                if is_valid(i, j, n):\n",
    "                    board[i][j] = str(n+1)\n",
    "                    row[i][n] = 1\n",
    "                    col[j][n] = 1\n",
    "                    box[i // 3 * 3 + j // 3][n] = 1\n",
    "                    if backtrack(index+1):\n",
    "                        return True\n",
    "                    board[i][j] = \".\"\n",
    "                    row[i][n] = 0\n",
    "                    col[j][n] = 0\n",
    "                    box[i // 3 * 3 + j // 3][n] = 0\n",
    "            return False\n",
    "\n",
    "        backtrack(0)\n",
    "                        \n",
    "            \n",
    "            \n",
    "\n",
    "            \n",
    "\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        return self.backtrack(board, 0, 0)\n",
    "    def backtrack(self,board:List[List[str]], i:int,j:int) ->None:\n",
    "        m, n = 9, 9\n",
    "        if j == n:\n",
    "            return self.backtrack(board, i+1, 0)\n",
    "        if i == m:\n",
    "            return True\n",
    "        if board[i][j] != '.':\n",
    "            return  self.backtrack(board, i, j+1)\n",
    "        for ch in range(ord('1'),ord('9')+1):\n",
    "            ch = chr(ch)\n",
    "            if not self.isValid(board, i, j, ch):\n",
    "                continue\n",
    "            board[i][j] = ch\n",
    "            if self.backtrack(board, i, j+1):\n",
    "                return True\n",
    "            board[i][j] = '.'\n",
    "        return False    \n",
    "    def isValid(self,board:List[List[str]], r:int,c:int,n:int) ->bool:\n",
    "        for i in range(9):\n",
    "            if board[r][i] == n:\n",
    "                return False\n",
    "            if board[i][c] == n:\n",
    "                return False\n",
    "            if board[(r//3)*3+i//3][(c//3)*3+i%3] == n:\n",
    "                return False\n",
    "        return True    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        self.backtracking(board)\n",
    "\n",
    "    def backtracking(self, board: List[List[str]]) -> bool:\n",
    "        # 若有解，返回True；若无解，返回False\n",
    "        for i in range(len(board)): # 遍历行\n",
    "            for j in range(len(board[0])):  # 遍历列\n",
    "                # 若空格内已有数字，跳过\n",
    "                if board[i][j] != '.': continue\n",
    "                for k in range(1, 10):\n",
    "                    if self.is_valid(i, j, k, board):\n",
    "                        board[i][j] = str(k)\n",
    "                        if self.backtracking(board): return True\n",
    "                        board[i][j] = '.'\n",
    "                # 若数字1-9都不能成功填入空格，返回False无解\n",
    "                return False\n",
    "        return True # 有解\n",
    "\n",
    "    def is_valid(self, row: int, col: int, val: int, board: List[List[str]]) -> bool:\n",
    "        # 判断同一行是否冲突\n",
    "        for i in range(9):\n",
    "            if board[row][i] == str(val):\n",
    "                return False\n",
    "        # 判断同一列是否冲突\n",
    "        for j in range(9):\n",
    "            if board[j][col] == str(val):\n",
    "                return False\n",
    "        # 判断同一九宫格是否有冲突\n",
    "        start_row = (row // 3) * 3\n",
    "        start_col = (col // 3) * 3\n",
    "        for i in range(start_row, start_row + 3):\n",
    "            for j in range(start_col, start_col + 3):\n",
    "                if board[i][j] == str(val):\n",
    "                    return False\n",
    "        return True\n",
    "        \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        nums = {'1', '2', '3', '4', '5', '6', '7', '8', '9'}\n",
    "        row = [set() for _ in range(9)]\n",
    "        column = [set() for _ in range(9)]\n",
    "        table = [[set() for _ in range(3)] for _ in range(3)]\n",
    "        empty = []\n",
    "\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                num = board[i][j]\n",
    "                if num == \".\":\n",
    "                    empty.append((i, j))\n",
    "                else:\n",
    "                    row[i].add(num)\n",
    "                    column[j].add(num)\n",
    "                    table[i//3][j//3].add(num)\n",
    "\n",
    "        def dfs(n):\n",
    "            if n == len(empty): return True\n",
    "            i, j = empty[n]\n",
    "            choice = nums - row[i] - column[j] - table[i//3][j//3]\n",
    "            for num in choice:\n",
    "                \n",
    "                row[i].add(num)\n",
    "                column[j].add(num)\n",
    "                table[i//3][j//3].add(num)\n",
    "                if dfs(n + 1): \n",
    "                    board[i][j] = num\n",
    "                    return True\n",
    "                row[i].remove(num)\n",
    "                column[j].remove(num)\n",
    "                table[i//3][j//3].remove(num)\n",
    "\n",
    "        dfs(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        self.back(board)\n",
    "        return board\n",
    "\n",
    "\n",
    "    def back(self, board):\n",
    "\n",
    "        # 若有解，返回True；若无解，返回False\n",
    "        for i in range(9): # 遍历行\n",
    "            for j in range(9):  # 遍历列\n",
    "\n",
    "                # 若空格内已有数字，跳过\n",
    "                if board[i][j] != '.': \n",
    "                    continue\n",
    "\n",
    "                for k in range(1, 10):\n",
    "                    if self.islegitimate(board, i, j, str(k)):\n",
    "                        board[i][j] = str(k)\n",
    "                        \n",
    "                        find = self.back(board)\n",
    "                        \n",
    "                        if find == True: \n",
    "                            return True\n",
    "\n",
    "                        board[i][j] = '.'\n",
    "\n",
    "                # 若数字1-9都不能成功填入空格，返回False无解\n",
    "                return False\n",
    "\n",
    "        return True # 有解\n",
    "\n",
    "\n",
    "\n",
    "    def islegitimate(self, board, y, x, value):\n",
    "\n",
    "        for i in range(9):\n",
    "            if board[y][i] == value or board[i][x] == value:\n",
    "                return False\n",
    "\n",
    "        start_x = (x // 3) * 3\n",
    "        start_y = (y // 3) * 3\n",
    "        for i in range(start_x, start_x + 3):\n",
    "            for j in range(start_y, start_y + 3):\n",
    "                if board[j][i] == value:\n",
    "                    return False\n",
    "\n",
    "        return True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        for i in range(81):\n",
    "            if board[i//9][i % 9] == '.':\n",
    "                for j in range(9):\n",
    "                    if self.ifok(board, j+1, [i//9, i % 9]):\n",
    "                        # b2 = copy.deepcopy(board)\n",
    "                        # b2[i//9][i % 9] = str(j+1)\n",
    "                        # elseok = self.solveSudoku(b2)\n",
    "                        board[i//9][i % 9] = str(j+1)\n",
    "                        elseok = self.solveSudoku(board)\n",
    "                        if not elseok:\n",
    "                            board[i//9][i % 9] = '.'\n",
    "                            continue\n",
    "                        else:\n",
    "                            return True\n",
    "                return False\n",
    "        return True\n",
    "\n",
    "    def ifok(self, board, n, place):\n",
    "        for i in range(9):\n",
    "            if board[place[0]][i] != '.' and int(board[place[0]][i]) == n:\n",
    "                return False\n",
    "        for i in range(9):\n",
    "            if board[i][place[1]] != '.' and int(board[i][place[1]]) == n:\n",
    "                return False\n",
    "        block = []\n",
    "        block.append(place[0]//3*3)\n",
    "        block.append(place[1]//3*3)\n",
    "        for i in range(3):\n",
    "            for j in range(3):\n",
    "                if board[block[0]+i][block[1]+j] != '.' and int(board[block[0]+i][block[1]+j]) == n:\n",
    "                    return False\n",
    "        return True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        n = len(board)\n",
    "        row_memo = [[False] * n for _ in range(n)] \n",
    "        col_memo = [[False] * n for _ in range(n)] \n",
    "        block = [[[False] * n for _ in range(n//3)] for _ in range(n//3)]\n",
    "        space = []\n",
    "        valid = False\n",
    "        for i in range(n):\n",
    "            for j in range(n):\n",
    "                if (board[i][j] == \".\"):\n",
    "                    space.append((i, j))\n",
    "                else:\n",
    "                    digit = int(board[i][j]) - 1\n",
    "                    row_memo[i][digit] = True\n",
    "                    col_memo[j][digit] = True\n",
    "                    block[i//3][j//3][digit] = True\n",
    "        \n",
    "        def backtrack(index):\n",
    "            nonlocal valid\n",
    "            if (index == len(space)):\n",
    "                valid = True\n",
    "                return              \n",
    "            (i, j) = space[index]\n",
    "            for k in range(1, 10):\n",
    "                if (valid == True):\n",
    "                    return\n",
    "                if (row_memo[i][k-1] == False and col_memo[j][k-1] == False and block[i//3][j//3][k-1] == False):\n",
    "                    row_memo[i][k-1] = True\n",
    "                    col_memo[j][k-1] = True\n",
    "                    block[i//3][j//3][k-1] = True\n",
    "                    board[i][j] = str(k)\n",
    "                    backtrack(index+1)\n",
    "                    row_memo[i][k-1] = False\n",
    "                    col_memo[j][k-1] = False\n",
    "                    block[i//3][j//3][k-1] = False\n",
    "\n",
    "        backtrack(0)\n",
    "        return\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def __init__(self):\n",
    "        \n",
    "        self.rows = [set() for _ in range(9)]\n",
    "        self.columns = [set() for _ in range(9)]\n",
    "        self.subboxes = [[set() for _ in range(9)] for _ in range(3)]\n",
    "    \n",
    "    def isValidSudoku(self, board, row, col, num):\n",
    "        if num in self.rows[row] or num in self.columns[col] or num in self.subboxes[row//3][col//3]:\n",
    "            return False\n",
    "        return True\n",
    "\n",
    "    def solveSudoku(self, board):\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if board[i][j] != '.':\n",
    "                    self.rows[i].add(board[i][j])\n",
    "                    self.columns[j].add(board[i][j])\n",
    "                    self.subboxes[i//3][j//3].add(board[i][j])\n",
    "        \n",
    "        self._solve(board)\n",
    "\n",
    "    def _solve(self, board):\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if board[i][j] == '.':\n",
    "                    for num in map(str, range(1,10)):\n",
    "                        if self.isValidSudoku(board, i, j, num):\n",
    "                            board[i][j] = num\n",
    "                            self.rows[i].add(num)\n",
    "                            self.columns[j].add(num)\n",
    "                            self.subboxes[i//3][j//3].add(num)\n",
    "\n",
    "                            if self._solve(board):\n",
    "                                return True\n",
    "\n",
    "                            board[i][j] = '.'\n",
    "                            self.rows[i].remove(num)\n",
    "                            self.columns[j].remove(num)\n",
    "                            self.subboxes[i//3][j//3].remove(num)\n",
    "                    return False\n",
    "\n",
    "        return True\n",
    "\n",
    "                        \n",
    "\n",
    "        \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        n = len(board)\n",
    "        row_memo = [[False] * n for _ in range(n)] \n",
    "        col_memo = [[False] * n for _ in range(n)] \n",
    "        block = [[[False] * n for _ in range(n//3)] for _ in range(n//3)]\n",
    "        space = []\n",
    "        valid = False\n",
    "        for i in range(n):\n",
    "            for j in range(n):\n",
    "                if (board[i][j] == \".\"):\n",
    "                    space.append((i, j))\n",
    "                else:\n",
    "                    digit = int(board[i][j]) - 1\n",
    "                    row_memo[i][digit] = True\n",
    "                    col_memo[j][digit] = True\n",
    "                    block[i//3][j//3][digit] = True\n",
    "        \n",
    "        def backtrack(index):\n",
    "            nonlocal valid\n",
    "            if (index == len(space)):\n",
    "                valid = True\n",
    "                return              \n",
    "            (i, j) = space[index]\n",
    "            for k in range(1, 10):\n",
    "                if (valid == True):\n",
    "                    return\n",
    "                if (row_memo[i][k-1] == False and col_memo[j][k-1] == False and block[i//3][j//3][k-1] == False):\n",
    "                    row_memo[i][k-1] = True\n",
    "                    col_memo[j][k-1] = True\n",
    "                    block[i//3][j//3][k-1] = True\n",
    "                    board[i][j] = str(k)\n",
    "                    backtrack(index+1)\n",
    "                    row_memo[i][k-1] = False\n",
    "                    col_memo[j][k-1] = False\n",
    "                    block[i//3][j//3][k-1] = False\n",
    "\n",
    "        backtrack(0)\n",
    "        return\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        def dfs(pos: int):\n",
    "            nonlocal valid\n",
    "            if pos == len(spaces):\n",
    "                valid = True\n",
    "                return\n",
    "            \n",
    "            i, j = spaces[pos]\n",
    "            for digit in range(9):\n",
    "                if line[i][digit] == column[j][digit] == block[i // 3][j // 3][digit] == False:\n",
    "                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = True\n",
    "                    board[i][j] = str(digit + 1)\n",
    "                    dfs(pos + 1)\n",
    "                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = False\n",
    "                if valid:\n",
    "                    return\n",
    "            \n",
    "        line = [[False] * 9 for _ in range(9)]\n",
    "        column = [[False] * 9 for _ in range(9)]\n",
    "        block = [[[False] * 9 for _a in range(3)] for _b in range(3)]\n",
    "        valid = False\n",
    "        spaces = list()\n",
    "\n",
    "        for i in range(9): #遍历题目\n",
    "            for j in range(9):\n",
    "                if board[i][j] == \".\":\n",
    "                    spaces.append((i, j))\n",
    "                else:\n",
    "                    digit = int(board[i][j]) - 1\n",
    "                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = True\n",
    "\n",
    "        dfs(0)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\r\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\r\n",
    "        \"\"\"\r\n",
    "        Do not return anything, modify board in-place instead.\r\n",
    "        \"\"\"\r\n",
    "        self.backtrack(board, 0, 0)\r\n",
    "\r\n",
    "    def backtrack(self, board, row, col):\r\n",
    "        n = len(board)\r\n",
    "        if col == n:\r\n",
    "            return self.backtrack(board, row + 1, 0)\r\n",
    "        if row == n:\r\n",
    "            return True\r\n",
    "\r\n",
    "        if board[row][col] != '.':\r\n",
    "            # 预设数字，跳过\r\n",
    "            return self.backtrack(board, row, col + 1)\r\n",
    "    \r\n",
    "        for num in range(1, 10):\r\n",
    "            num = str(num)\r\n",
    "            # 不合法数字，跳过\r\n",
    "            if not self.isValid(board, row, col, num):\r\n",
    "                continue\r\n",
    "            # 可行解，填入\r\n",
    "            board[row][col] = num\r\n",
    "            if self.backtrack(board, row, col + 1):\r\n",
    "                return True\r\n",
    "            # 还原\r\n",
    "            board[row][col] = '.' \r\n",
    "        return False\r\n",
    "    \r\n",
    "    def isValid(self, board, r, c, num):\r\n",
    "        n = len(board)\r\n",
    "        # num = board[r][c]\r\n",
    "        # 检查行\r\n",
    "        for i in range(n):\r\n",
    "            if num == board[r][i] and i != c:\r\n",
    "            # if num == board[r][i]:\r\n",
    "                return False\r\n",
    "        # 检查列\r\n",
    "        for j in range(n):\r\n",
    "            if num == board[j][c] and j != r:\r\n",
    "            # if num == board[j][c]:\r\n",
    "                return False\r\n",
    "        # 检查九宫格\r\n",
    "        for i in range((r // 3) * 3, (r // 3) * 3 + 3):\r\n",
    "            for j in range((c // 3) * 3, (c // 3) * 3 + 3):\r\n",
    "                if num == board[i][j] and (i != r or j != c):\r\n",
    "                    return False\r\n",
    "        \r\n",
    "        # start_row, start_col = (r // 3) * 3, (c // 3) * 3\r\n",
    "        # for i in range(start_row, start_row + 3):\r\n",
    "        #     for j in range(start_col, start_col + 3):\r\n",
    "        #         if (i != r or j != c) and board[i][j] == num:\r\n",
    "        #             return False\r\n",
    "        \r\n",
    "        return True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        nums = {'1', '2', '3', '4', '5', '6', '7', '8', '9'}\n",
    "        row = [set() for _ in range(9)]\n",
    "        column = [set() for _ in range(9)]\n",
    "        table = [[set() for _ in range(3)] for _ in range(3)]\n",
    "        empty = []\n",
    "\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                num = board[i][j]\n",
    "                if num == \".\":\n",
    "                    empty.append((i, j))\n",
    "                else:\n",
    "                    row[i].add(num)\n",
    "                    column[j].add(num)\n",
    "                    table[i//3][j//3].add(num)\n",
    "\n",
    "        def dfs(n):\n",
    "            if n == len(empty): return True\n",
    "            i, j = empty[n]\n",
    "            choice = nums - row[i] - column[j] - table[i//3][j//3]\n",
    "            for num in choice:\n",
    "                board[i][j] = num\n",
    "                row[i].add(num)\n",
    "                column[j].add(num)\n",
    "                table[i//3][j//3].add(num)\n",
    "                if dfs(n + 1): \n",
    "                    return True\n",
    "                row[i].remove(num)\n",
    "                column[j].remove(num)\n",
    "                table[i//3][j//3].remove(num)\n",
    "\n",
    "        dfs(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        self.backtracking(board)\n",
    "\n",
    "    def backtracking(self, board: List[List[str]]) -> bool:\n",
    "        # 若有解，返回True；若无解，返回False\n",
    "        for i in range(len(board)): # 遍历行\n",
    "            for j in range(len(board[0])):  # 遍历列\n",
    "                # 若空格内已有数字，跳过\n",
    "                if board[i][j] != '.': continue\n",
    "                for k in range(1, 10):  \n",
    "                    if self.is_valid(i, j, k, board):\n",
    "                        board[i][j] = str(k)\n",
    "                        if self.backtracking(board): return True\n",
    "                        board[i][j] = '.'\n",
    "                # 若数字1-9都不能成功填入空格，返回False无解\n",
    "                return False\n",
    "        return True # 有解\n",
    "\n",
    "    def is_valid(self, row: int, col: int, val: int, board: List[List[str]]) -> bool:\n",
    "        # 判断同一行是否冲突\n",
    "        for i in range(9):\n",
    "            if board[row][i] == str(val):\n",
    "                return False\n",
    "        # 判断同一列是否冲突\n",
    "        for j in range(9):\n",
    "            if board[j][col] == str(val):\n",
    "                return False\n",
    "        # 判断同一九宫格是否有冲突\n",
    "        start_row = (row // 3) * 3\n",
    "        start_col = (col // 3) * 3\n",
    "        for i in range(start_row, start_row + 3):\n",
    "            for j in range(start_col, start_col + 3):\n",
    "                if board[i][j] == str(val):\n",
    "                    return False\n",
    "        return True\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        self.backtracking(board)\n",
    "\n",
    "    def backtracking(self, board: List[List[str]]) -> bool:\n",
    "        # 若有解，返回True；若无解，返回False\n",
    "        for i in range(len(board)): # 遍历行\n",
    "            for j in range(len(board[0])):  # 遍历列\n",
    "                # 若空格内已有数字，跳过\n",
    "                if board[i][j] != '.': continue\n",
    "                for k in range(1, 10):  \n",
    "                    if self.is_valid(i, j, k, board):\n",
    "                        board[i][j] = str(k)\n",
    "                        if self.backtracking(board): return True\n",
    "                        board[i][j] = '.'\n",
    "                # 若数字1-9都不能成功填入空格，返回False无解\n",
    "                return False\n",
    "        return True # 有解\n",
    "\n",
    "    def is_valid(self, row: int, col: int, val: int, board: List[List[str]]) -> bool:\n",
    "        # 判断同一行是否冲突\n",
    "        for i in range(9):\n",
    "            if board[row][i] == str(val):\n",
    "                return False\n",
    "        # 判断同一列是否冲突\n",
    "        for j in range(9):\n",
    "            if board[j][col] == str(val):\n",
    "                return False\n",
    "        # 判断同一九宫格是否有冲突\n",
    "        start_row = (row // 3) * 3\n",
    "        start_col = (col // 3) * 3\n",
    "        for i in range(start_row, start_row + 3):\n",
    "            for j in range(start_col, start_col + 3):\n",
    "                if board[i][j] == str(val):\n",
    "                    return False\n",
    "        return True\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        choice_pool = {'1', '2', '3', '4', '5', '6', '7', '8', '9'}\n",
    "        row = [set() for _ in range(9)]\n",
    "        column = [set() for _ in range(9)]\n",
    "        table = [[set() for _ in range(3)] for _ in range(3)]\n",
    "        to_be_filled = []\n",
    "\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                num = board[i][j]\n",
    "                if num == \".\":\n",
    "                    to_be_filled.append((i, j))\n",
    "                else:\n",
    "                    row[i].add(num)\n",
    "                    column[j].add(num)\n",
    "                    table[i//3][j//3].add(num)\n",
    "\n",
    "        def deepest_first_search(n):\n",
    "            if n == len(to_be_filled): return True\n",
    "            i, j = to_be_filled[n]\n",
    "            choice = choice_pool - row[i] - column[j] - table[i//3][j//3]\n",
    "            for num in choice:\n",
    "                row[i].add(num)\n",
    "                column[j].add(num)\n",
    "                table[i//3][j//3].add(num)\n",
    "                if deepest_first_search(n + 1): \n",
    "                    board[i][j] = num\n",
    "                    return True\n",
    "                row[i].remove(num)\n",
    "                column[j].remove(num)\n",
    "                table[i//3][j//3].remove(num)\n",
    "\n",
    "        deepest_first_search(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        def dfs(pos: int):\n",
    "            nonlocal valid\n",
    "            if pos == len(spaces):\n",
    "                valid = True\n",
    "                return\n",
    "            \n",
    "            i, j = spaces[pos]\n",
    "            for digit in range(9):\n",
    "                if line[i][digit] == column[j][digit] == block[i // 3][j // 3][digit] == False:\n",
    "                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = True\n",
    "                    board[i][j] = str(digit + 1)\n",
    "                    dfs(pos + 1)\n",
    "                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = False\n",
    "                if valid:\n",
    "                    return\n",
    "            \n",
    "        line = [[False] * 9 for _ in range(9)]\n",
    "        column = [[False] * 9 for _ in range(9)]\n",
    "        block = [[[False] * 9 for _a in range(3)] for _b in range(3)]\n",
    "        valid = False\n",
    "        spaces = list()\n",
    "\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if board[i][j] == \".\":\n",
    "                    spaces.append((i, j))\n",
    "                else:\n",
    "                    digit = int(board[i][j]) - 1\n",
    "                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = True\n",
    "\n",
    "        dfs(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        def possiblenum(i,j):\n",
    "            t=~(row[i]|col[j]|box[i//3][j//3])\n",
    "            return [i for i in range(9) if t&(1<<i)]\n",
    "        def getnext():\n",
    "            minn=10\n",
    "            a,b=0,0\n",
    "            for i in range(9):\n",
    "                for j in range(9):\n",
    "                    if(board[i][j]=='.'):\n",
    "                        t=possiblenum(i,j)\n",
    "                        n=len(t)\n",
    "                        if(n==1):\n",
    "                            return i,j\n",
    "                        elif(n<minn):\n",
    "                            a=i\n",
    "                            b=j\n",
    "                            minn=n\n",
    "            return a,b        \n",
    "        def fix_board(i,j,k,b):\n",
    "            if(b<0):\n",
    "                board[i][j]='.'\n",
    "                row[i]&=~(1<<(k))\n",
    "                col[j]&=~(1<<(k))\n",
    "                box[i//3][j//3]&=~(1<<(k))\n",
    "            else:\n",
    "                board[i][j]=str(k+1)\n",
    "                row[i]|=(1<<k)\n",
    "                col[j]|=(1<<k)\n",
    "                box[i//3][j//3]|=(1<<k)\n",
    "\n",
    "\n",
    "        def dfs(num):\n",
    "            if(num==0):\n",
    "                return True\n",
    "            i,j=getnext()\n",
    "            p=possiblenum(i,j)\n",
    "            for k in p:\n",
    "                fix_board(i,j,k,1)\n",
    "                if(dfs(num-1)):\n",
    "                    return True\n",
    "                fix_board(i,j,k,-1)\n",
    "            return False\n",
    "        row=[0 for i in range(9)]\n",
    "        col=[0 for i in range(9)]\n",
    "        box=[[0 for i in range(3)]for j in range(3)]\n",
    "        num=0\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if(board[i][j]=='.'):\n",
    "                    num+=1\n",
    "                else:\n",
    "                    p=int(board[i][j])-1\n",
    "                    row[i]|=(1<<p)\n",
    "                    col[j]|=(1<<p)\n",
    "                    box[i//3][j//3]|=(1<<p)\n",
    "        dfs(num)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        # 初始化行、列和宫的集合\n",
    "        lines = [set() for _ in range(9)]\n",
    "        cols = [set() for _ in range(9)]\n",
    "        sqs = [set() for _ in range(9)]\n",
    "        empty_list = []  # 存储空格位置的列表\n",
    "\n",
    "        # 遍历数独棋盘，初始化集合和空格列表\n",
    "        for i, line in enumerate(board):\n",
    "            for j, ch in enumerate(line):\n",
    "                if ch == '.':\n",
    "                    empty_list.append((i, j))\n",
    "                else:\n",
    "                    lines[i].add(ch)\n",
    "                    cols[j].add(ch)\n",
    "                    sqs[(i // 3) * 3 + (j // 3)].add(ch)\n",
    "\n",
    "        res = []  # 存储填充结果的列表\n",
    "\n",
    "        def dfs(k):\n",
    "            # 递归终止条件：如果所有空格都填充完毕，返回True\n",
    "            if k == len(empty_list):\n",
    "                return True\n",
    "\n",
    "            i, j = empty_list[k]\n",
    "\n",
    "            # 尝试填入数字'1'到'9'\n",
    "            for ch in '123456789':\n",
    "                if not (ch in lines[i] or ch in cols[j] or ch in sqs[(i // 3) * 3 + (j // 3)]):\n",
    "                    # 如果数字在当前行、列、宫中均不存在，填入并更新相关集合\n",
    "                    lines[i].add(ch)\n",
    "                    cols[j].add(ch)\n",
    "                    sqs[(i // 3) * 3 + (j // 3)].add(ch)\n",
    "                    res.append(ch)\n",
    "\n",
    "                    # 递归填充下一个空格\n",
    "                    if dfs(k+1):\n",
    "                        return True\n",
    "\n",
    "                    # 回溯：如果无法成功填充下一个空格，撤销当前填充，继续尝试其他数字\n",
    "                    res.pop()\n",
    "                    lines[i].remove(ch)\n",
    "                    cols[j].remove(ch)\n",
    "                    sqs[(i // 3) * 3 + (j // 3)].remove(ch)\n",
    "\n",
    "            # 如果无法找到合适的数字填充当前空格，返回False\n",
    "            return False\n",
    "\n",
    "        # 调用DFS函数开始填充数独\n",
    "        dfs(0)\n",
    "\n",
    "        # 将填充结果更新到数独棋盘中\n",
    "        for (i, j), r in zip(empty_list, res):\n",
    "            board[i][j] = r"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        \"\"\"\n",
    "        Do not return anything, modify board in-place instead.\n",
    "        \"\"\"\n",
    "        \n",
    "        lines = [set() for _ in range(9)]\n",
    "        cols = [set() for _ in range(9)]\n",
    "        sqs = [set() for _ in range(9)]\n",
    "        empty_list = []  # 存储空格位置的列表\n",
    "\n",
    "        \n",
    "        for i, line in enumerate(board):\n",
    "            for j, ch in enumerate(line):\n",
    "                if ch == '.':\n",
    "                    empty_list.append((i, j))\n",
    "                else:\n",
    "                    lines[i].add(ch)\n",
    "                    cols[j].add(ch)\n",
    "                    sqs[(i // 3) * 3 + (j // 3)].add(ch)\n",
    "\n",
    "        res = []\n",
    "\n",
    "        def dfs(k):\n",
    "            \n",
    "            if k == len(empty_list):\n",
    "                return True\n",
    "\n",
    "            i, j = empty_list[k]\n",
    "\n",
    "            \n",
    "            for ch in '123456789':\n",
    "                if not (ch in lines[i] or ch in cols[j] or ch in sqs[(i // 3) * 3 + (j // 3)]):\n",
    "                   \n",
    "                    lines[i].add(ch)\n",
    "                    cols[j].add(ch)\n",
    "                    sqs[(i // 3) * 3 + (j // 3)].add(ch)\n",
    "                    res.append(ch)\n",
    "\n",
    "                    \n",
    "                    if dfs(k+1):\n",
    "                        return True\n",
    "\n",
    "                    \n",
    "                    res.pop()\n",
    "                    lines[i].remove(ch)\n",
    "                    cols[j].remove(ch)\n",
    "                    sqs[(i // 3) * 3 + (j // 3)].remove(ch)\n",
    "\n",
    "           \n",
    "            return False\n",
    "\n",
    "       \n",
    "        dfs(0)\n",
    "\n",
    "        \n",
    "        for (i, j), r in zip(empty_list, res):\n",
    "            board[i][j] = r"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solveSudoku(self, board: List[List[str]]) -> None:\n",
    "        def dfs(pos: int):\n",
    "            nonlocal valid\n",
    "            if pos == len(spaces):\n",
    "                valid = True\n",
    "                return\n",
    "            \n",
    "            i, j = spaces[pos]\n",
    "            for digit in range(9):\n",
    "                if line[i][digit] == column[j][digit] == block[i // 3][j // 3][digit] == False:\n",
    "                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = True\n",
    "                    board[i][j] = str(digit + 1)\n",
    "                    dfs(pos + 1)\n",
    "                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = False\n",
    "                if valid:\n",
    "                    return\n",
    "            \n",
    "        line = [[False] * 9 for _ in range(9)]\n",
    "        column = [[False] * 9 for _ in range(9)]\n",
    "        block = [[[False] * 9 for _a in range(3)] for _b in range(3)]\n",
    "        valid = False\n",
    "        spaces = list()\n",
    "\n",
    "        for i in range(9):\n",
    "            for j in range(9):\n",
    "                if board[i][j] == \".\":\n",
    "                    spaces.append((i, j))\n",
    "                else:\n",
    "                    digit = int(board[i][j]) - 1\n",
    "                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = True\n",
    "\n",
    "        dfs(0)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def subsetXORSum(self, nums: List[int]) -> int:\n",
    "        res = []\n",
    "        n = len(nums)\n",
    "        def solve(start,list_):\n",
    "            for i in range(start,n):\n",
    "                list_.append(nums[i])\n",
    "                res.append(list_.copy())\n",
    "                solve(i+1,list_)\n",
    "                list_.pop()\n",
    "        solve(0,[])\n",
    "        m = len(res)\n",
    "        ans = 0\n",
    "        print(res)\n",
    "        for i in range(m):\n",
    "            num = res[i][0]\n",
    "            k = len(res[i])\n",
    "            for j in range(1,k):\n",
    "                num ^= res[i][j]\n",
    "            ans += num\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solve(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n",
    "        n, m = len(nums), len(queries)\n",
    "        res, d, mod = [0] * m, {}, 10**9+7\n",
    "        for idx in sorted(range(m), key=lambda x: -queries[x][0]):\n",
    "            x, y = queries[idx]\n",
    "            nx, ns = d.get((x%y, y), (n, 0))\n",
    "            s = (sum(nums[x:nx:y])+ns) % mod\n",
    "            res[idx] = s\n",
    "            d[(x%y, y)] = (x, s)\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solve(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n",
    "        mod = 10**9+7\n",
    "        n = len(nums)\n",
    "        res, d = [0]*len(queries), {}\n",
    "        for i,(x,y) in sorted(enumerate(queries),key=lambda p:-p[1][0]):\n",
    "            nx,ns = d.get((x%y,y),(n,0))\n",
    "            s = (ns+sum(nums[x:nx:y]))%mod\n",
    "            res[i] = s \n",
    "            d[(x%y,y)] = (x,s)\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solve(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n",
    "        mod = 10**9+7\n",
    "        n = len(nums)\n",
    "        res, d = [0]*len(queries), {}\n",
    "        for i,(x,y) in sorted(enumerate(queries),key=lambda p:-p[1][0]):\n",
    "            nx,ns = d.get((x%y,y),(n,0))\n",
    "            s = (ns+sum(nums[x:nx:y]))%mod\n",
    "            res[i] = s \n",
    "            d[(x%y,y)] = (x,s)\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solve(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n",
    "        mod = 10**9+7\n",
    "        m = len(queries)\n",
    "        g = defaultdict(list)\n",
    "        for i,(x,y) in enumerate(queries):\n",
    "            g[(x%y,y)].append((x,i))\n",
    "        res = [0]*m\n",
    "        for (_,y),A in g.items():\n",
    "            s,pre = 0, len(nums)\n",
    "            for x,i in sorted(A)[::-1]:\n",
    "                s += sum(nums[x:pre:y])\n",
    "                s %= mod\n",
    "                res[i] = s\n",
    "                pre = x\n",
    "        return res\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solve(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n",
    "        n=len(nums)\n",
    "        k=201\n",
    "        mod=10**9+7\n",
    "        dp=[[0]*k for _ in range(n)]\n",
    "        for i in range(n-1,-1,-1):\n",
    "            for j in range(1,k):\n",
    "                dp[i][j]+=nums[i]\n",
    "                dp[i][j]%=mod\n",
    "                if i-j>=0:\n",
    "                    dp[i-j][j]+=dp[i][j]\n",
    "        res=[]\n",
    "        for x,y in queries:\n",
    "            if y<k:\n",
    "                res.append(dp[x][y])\n",
    "            else:\n",
    "                s=0\n",
    "                while x<n:\n",
    "                    s+=nums[x]\n",
    "                    x+=y\n",
    "                res.append(s%mod)\n",
    "        return res\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solve(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n",
    "        n=len(nums)\n",
    "        k=221\n",
    "        mod=10**9+7\n",
    "        dp=[[0]*k for _ in range(n)]\n",
    "        for i in range(n-1,-1,-1):\n",
    "            for j in range(1,k):\n",
    "                dp[i][j]+=nums[i]\n",
    "                dp[i][j]%=mod\n",
    "                if i-j>=0:\n",
    "                    dp[i-j][j]+=dp[i][j]\n",
    "        res=[]\n",
    "        for x,y in queries:\n",
    "            if y<k:\n",
    "                res.append(dp[x][y])\n",
    "            else:\n",
    "                s=0\n",
    "                while x<n:\n",
    "                    s+=nums[x]\n",
    "                    x+=y\n",
    "                res.append(s%mod)\n",
    "        return res\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def solve(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n",
    "        n=len(nums)\n",
    "        k=int(sqrt(n))\n",
    "        mod=10**9+7\n",
    "        dp=[[0]*k for _ in range(n)]\n",
    "        for i in range(n-1,-1,-1):\n",
    "            for j in range(1,k):\n",
    "                dp[i][j]+=nums[i]\n",
    "                dp[i][j]%=mod\n",
    "                if i-j>=0:\n",
    "                    dp[i-j][j]+=dp[i][j]\n",
    "        res=[]\n",
    "        for x,y in queries:\n",
    "            if y<k:\n",
    "                res.append(dp[x][y])\n",
    "            else:\n",
    "                s=0\n",
    "                while x<n:\n",
    "                    s+=nums[x]\n",
    "                    x+=y\n",
    "                res.append(s%mod)\n",
    "        return res\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from math import floor, sqrt\n",
    "from typing import List\n",
    "\n",
    "class Solution:\n",
    "    def solve(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n",
    "        n = len(nums)\n",
    "        sqrtn = floor(sqrt(n))\n",
    "        pre = [[0 for _ in range(n)] for _ in range(sqrtn+1)]\n",
    "        for i in range(1, sqrtn+1):\n",
    "            for j in range(n-1, n-i-1, -1):\n",
    "                pre[i][j] = nums[j]\n",
    "\n",
    "            for j in range(n-i-1, -1, -1):\n",
    "                pre[i][j] = pre[i][j+i] + nums[j]\n",
    "        \n",
    "        mod = 10**9 + 7\n",
    "        res = []\n",
    "        for x, y in queries:            \n",
    "            if y > sqrtn:\n",
    "                val = 0\n",
    "                while x < n:\n",
    "                    val += nums[x]\n",
    "                    x += y\n",
    "            else:\n",
    "                val = pre[y][x]\n",
    "            res.append(val%mod)\n",
    "        return res\n"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 2
}
